I am trying to create an app that will get some information from a server, using volley. You should enter your info in, and then click login at the bottom, but for somereason it keeps crashing.
First and foremost when the button is clicked, it crashes and the logcat is:
https://pastebin.com/deQi874r
Main Activity code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
TextView textView = (TextView)findViewById(R.id.currentFragDisplay);
textView.setText("My Profile");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmentContainer, new Personal_Profile_Fragment());
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toolbar_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
switch (item_id) {
case R.id.accDetails:
swapFragment(item_id);
return true;
case R.id.personalProfileLookup:
swapFragment(item_id);
return true;
case R.id.favoriteCharacters:
swapFragment(item_id);
return true;
case R.id.friendProfileLookup:
swapFragment(item_id);
return true;
case R.id.tipsAndTricks:
swapFragment(item_id);
return true;
}
return false;
}
private void swapFragment(int fragmentID){
TextView tracker = (TextView) findViewById(R.id.currentFragDisplay);
Fragment fragment = null;
if(fragmentID == R.id.personalProfileLookup) {
tracker.setText("My Profile");
fragment = new Personal_Profile_Fragment();
} else if(fragmentID == R.id.favoriteCharacters) {
tracker.setText("Favorite Characters");
fragment = new Favorite_Characters_Fragment();
} else if(fragmentID == R.id.friendProfileLookup) {
tracker.setText("Friend Lookup");
fragment = new Friend_Profile_Fragment();
} else if(fragmentID == R.id.tipsAndTricks) {
tracker.setText("Tips and Tricks");
fragment = new TipsandTricks_Fragment();
} else if(fragmentID == R.id.accDetails) {
tracker.setText("Log In");
fragment = new loginFragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
login fragment(where button is):
public class loginFragment extends Fragment {
//Local Vars
private boolean loginCheck = false;
//required constructor
public loginFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
login(v);
}
});
// Inflate the layout for this fragment
return view;
}
public boolean isLoggedIn() {
return loginCheck;
}
private void login(View v){
Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_LONG).show();
String username;
String password;
username = v.findViewById(R.id.enteredUsername).toString();
password = v.findViewById(R.id.enteredPassword).toString();
final ArrayList<String> info = new ArrayList<>();
String[] unameSeparated = new String[username.length()];
unameSeparated = username.split("(?!^)");
String startUrl = "https://us.api.battle.net/d3/profile/";
String uname = "";
String APIKey = "/?locale=en_US&apikey=6nguxckrzchn86q9792jvdhww4uxf32v";
//Separating the username into the parts needed for sending request
for (int i = 0; i < unameSeparated.length; i++) {
if ((unameSeparated[i].equals("#"))) {
//Replacing # with '%23'
uname += "%23";
} else {
uname += unameSeparated[i];
}
}
String url = startUrl + uname+ APIKey;
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
info.add(response);
Toast.makeText(getActivity(),"Request Success",Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Request FAIL",Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
}
The problem is with you login click. You are passing the button and not the view in
login(v);
The V you are passing is an instance of the button not the view. So this
username = v.findViewById(R.id.enteredUsername).toString();
password = v.findViewById(R.id.enteredPassword).toString();
would be refering to a null pointer. Hope this helps
Related
Hello so I have a MainActivity which consists of two fragments one is home and the other notifications.
When the app is opened by default the Home fragment is displayed.My app has a navigation bar which comes with an app bar by default where all the Menu Items are inflated.
My home fragment consists of Posts and in the app bar there's a search icon (SearchView) when i click it and search for something nothing happens.
HomeFragment.java
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private HomeFragment.OnFragmentInteractionListener mListener;
private RecyclerView rv;
private FirebaseAuth fba;
private List<PostActivity> postItems;
private FirebaseUser user;
private Toolbar toolbar;
private PostAdapter pa;
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
user = FirebaseAuth.getInstance().getCurrentUser();
fba = FirebaseAuth.getInstance();
// dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles");
rv =view.findViewById(R.id.rvPostItems);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
rv.setLayoutManager(layoutManager);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postItems = new ArrayList<>();
rv.addItemDecoration(new DividerItemDecoration(rv.getContext(), DividerItemDecoration.VERTICAL));
loadPosts();
registerForContextMenu(rv);
return view;
}
public void loadPosts() {
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("Posts");
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postItems.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
PostActivity pac = ds.getValue(PostActivity.class);
postItems.add(pac);
pa = new PostAdapter(postItems, getActivity());
rv.setAdapter(pa);
pa.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), "Failed !", Toast.LENGTH_SHORT).show();
}
});
}
public void searchPosts(String query){
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("Posts");
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postItems.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
PostActivity pac = ds.getValue(PostActivity.class);
if(pac.getDesc().toLowerCase().contains(query.toLowerCase())) {
postItems.add(pac);
}
pa = new PostAdapter(postItems, getActivity());
rv.setAdapter(pa);
pa.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), "Failed !", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.main,menu);
MenuItem searchPosts = menu.findItem(R.id.searchPosts);
SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchPosts);
/*searchView.setIconified(true);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));*/
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
if(!TextUtils.isEmpty(s))
searchPosts(s);
else
loadPosts();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(!TextUtils.isEmpty(s))
searchPosts(s);
else
loadPosts();
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof HomeFragment.OnFragmentInteractionListener) {
mListener = (HomeFragment.OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements
,HomeFragment.OnFragmentInteractionListener
,NotificationFragment.OnFragmentInteractionListener{
private FirebaseAuth fba;
private FirebaseUser user;
private TextView welcomeUser;
private DatabaseReference dr;
private String name, thumb;
private Toolbar toolbar;
private MaterialSearchView msv;
private FloatingActionButton addPost;
private HomeFragment homeFragment;
private NotificationFragment notificationFragment;
private BottomNavigationView bnv;
private ImageView navImg;
private MenuItem itemToHide;
private Menu postsMenu = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fba = FirebaseAuth.getInstance();
/*if(!fba.getCurrentUser().isEmailVerified()){
fba.getCurrentUser().updateEmail(fba.getCurrentUser().getEmail());
fba.getCurrentUser().sendEmailVerification();
}*/
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Newsy");
addPost = findViewById(R.id.add_post_btn);
addPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,AddPost.class);
startActivity(intent);
}
});
if (!(fba.getCurrentUser().isEmailVerified()) || fba.getCurrentUser() == null) {
startActivity(new Intent(this, LoginScreen.class));
}
/*if(fba.getCurrentUser()==null ){
startActivity(new Intent(this,LoginScreen.class));
}*/
ConnectionDetector cd = new ConnectionDetector(this);
if(cd.isConnected()){
Toast.makeText(this,"Connection Established !",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"Your phone is Offline,Check your connection !",Toast.LENGTH_LONG).show();
}
user = fba.getCurrentUser();
String id = user.getUid();
dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles").child(id);
//ConstraintLayout cl = (ConstraintLayout)findViewById(R.id.LoginScreen);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
if (drawer != null) {
drawer.addDrawerListener(toggle);
}
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles").child(fba.getCurrentUser().getUid());
if (navigationView != null) {
navigationView.setNavigationItemSelectedListener(this);
View nav_header = navigationView.getHeaderView(0);
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
name = dataSnapshot.child("name").getValue().toString();
thumb = dataSnapshot.child("image").getValue().toString();
CircleImageView circle = (CircleImageView) nav_header.findViewById(R.id.navImg);
Picasso.get().load(thumb).placeholder(R.drawable.default_avatar).into(circle);
welcomeUser = (TextView) nav_header.findViewById(R.id.WelcomeUser);
welcomeUser.setText(name);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(pappuLayout);
Menu menu = navigationView.getMenu();
MenuItem mt = menu.findItem(nav_gallery);
mt.setTitle("News 2");
MenuItem mt2 = menu.findItem(nav_camera);
mt2.setTitle("News 1");
MenuItem mt3 = menu.findItem(nav_sub);
mt3.setTitle("Subscribe !");
//FRAGMENTS MAIN PAGE
bnv = findViewById(R.id.bottomNavigationView2);
homeFragment = new HomeFragment();
replaceFragment(new HomeFragment());
bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.bottomHome) {
replaceFragment(homeFragment);
return true;
} else if (itemId == R.id.bottomNotification) {
notificationFragment = new NotificationFragment();
replaceFragment(notificationFragment);
return true;
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = fba.getCurrentUser();
String id = user.getUid();
SharedPreferences sp = getSharedPreferences("USER", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Current_User", id);
editor.apply();
Intent intent = new Intent(getBaseContext(), MyUnityPlugin.class);
intent.putExtra("id", id);
dr.child("onlineStatus").setValue("true");
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser user = fba.getCurrentUser();
dr.child("onlineStatus").setValue(ServerValue.TIMESTAMP);
}
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.LogOut) {
fba.signOut();
finish();
startActivity(new Intent(this,LoginScreen.class));
return true;
}else if(id==R.id.settings){
startActivity(new Intent(this,ProfileActivity.class));
return true;
}else if(id==R.id.users){
startActivity(new Intent(this,Users.class));
return true;
}else if(id==R.id.search){
startActivity(new Intent(this,Users.class));
return true;
} else if (id == R.id.notificationSettings) {
startActivity(new Intent(this, SettingsActivity.class));
//startActivity(new Intent(this,UnityPlayerActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
if (itemId == R.id.nav_gallery) {
fragment = new GalleryFrag();
} else if (itemId == R.id.nav_camera) {
fragment = new CameraFrag();
} else if (itemId == R.id.nav_sub) {
fragment = new Subscribe();
} else if (itemId == R.id.nav_chat) {
fragment = new Chat();
} else if (itemId == R.id.nav_send) {
Intent i = new Intent(MainActivity.this, UnityPlayerActivity.class);
startActivity(i);
}
//replacing the fragment
if (fragment != null) {
ConstraintLayout fl = (ConstraintLayout) findViewById(pappuLayout);
fl.removeAllViews();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(pappuLayout, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(drawer_layout);
if (drawer != null) {
drawer.closeDrawer(GravityCompat.START);
}
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private void replaceFragment(Fragment fragment){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.postPage,fragment);
ft.addToBackStack(null);
ft.commit();
}
}
main.xml (Menu XML file)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="#+id/search"
android:title="Search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_action_search"
android:iconTint="#fff"
app:showAsAction="ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:visible="false"
>
</item>
<item
android:id="#+id/searchPosts"
android:title="Search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_action_search"
android:iconTint="#fff"
app:showAsAction="ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView"
>
</item>
<item
android:id="#+id/notificationSettings"
android:icon="#drawable/baseline_settings_applications_white_18dp"
android:orderInCategory="100"
android:title="Settings"
app:showAsAction="ifRoom">
</item>
<item
android:id="#+id/LogOut"
android:orderInCategory="100"
android:title="Log Out"
app:showAsAction="never" />
<item
android:id="#+id/settings"
android:title="My Profile! "
>
</item>
<item
android:id="#+id/users"
android:title="All users"
>
</item>
</menu>
I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.
i m following some guide to pass parameter from login to one fragment.
I have this structure (login page, user area (main activity that cointain only a fragment and some fragment)
I try to do this :
public class UserAreaActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener{
ProgressDialog progressDialog;
#Override
public void onBackPressed() {
//super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.anto.fitfix.R.layout.activity_user_area);
Bundle b = getIntent().getExtras();
final String name = b.getString("name");
final String user = b.getString("id");
final String email = b.getString("email");
final String gender = b.getString("gender");
final String photourl= b.getString("photo");
final String birthday = b.getString("birthday");
final String p="null";
Log.d("nome",""+name);
// loadFragment(new fragment_home());
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
BottomNavigationView navigation = findViewById(R.id.navigationView);
navigation.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment_home fragment = null;
switch (item.getItemId()) {
case R.id.action_home:
fragment = new fragment_home();
break;
case R.id.action_cron:
fragment = new fragment_home();
break;
case R.id.action_face:
// fragment = new NotificationsFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(android.support.v4.app.Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
and this for fragment
public class fragment_home extends Fragment {
ProgressDialog progressDialog;
String name,email,user,p;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
View view = inflater.inflate(R.layout.fragment_home, container, false);
TextView tResult = (TextView) view.findViewById(R.id.tResult);
TextView tMail = (TextView) view.findViewById(com.example.anto.fitfix.R.id.tMail);
TextView tAge = (TextView) view.findViewById(R.id.tAge);
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt("name");
Log.d("name",""+myInt);
tResult.setText(name);
}
BLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("wait..."); // Setting Message
progressDialog.setTitle("Logout"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
disconnectFromFacebook();
Thread.sleep(1600);
Intent fbIntent = new Intent(getActivity(), LoginActivity.class);
getActivity().startActivity(fbIntent);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
}
});
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
} catch (JSONException e) {
e.printStackTrace();
}
}
};
/* FbActivity registerRequest = new FbActivity(name, user, p, email, responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(registerRequest);*/
return view;
}
}
I recived the name from login , but i cant pass in fragment section..
Someone can give me the suggestion?
When you pass a bundle to fragment, you do not create an object of Fragment class, but instead you create the object of the fragment you created i.e fragment_home
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
Change the above code with the code below
fragment_home fragment = new fragment_home();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
In my app I have the following navigationview.
So when the user click the menu item Καλώς ήρθες(meaning welcome in Greek),I want the this to be shown in the toolbar. This is my code for the navigationview.
public class Welcome extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private SessionManager session;
Toolbar toolbar;
private int mIconSize;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(getApplicationContext());
SharedPreferences userName = PreferenceManager.getDefaultSharedPreferences(this);
//UserId = userName.getString("id","");
username = userName.getString("user_name", "");
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
if (savedInstanceState == null) {
//Restore the fragment's instance and geo coordinates!
//homeFragment = (FragmentHome) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
setSelected(R.id.welcome);
}else{
//profileFragment = (FragmentProfile) fm2.findFragmentByTag(PROFILE_FRAGMENT);
}
ActionBarDrawerToggle adt = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
R.string.open_drawer,R.string.close_drawer){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.addDrawerListener(adt);
adt.syncState();
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setBackgroundColor(getResources().getColor(R.color.navigation_bg_color));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
boolean result = setSelected(item.getItemId());
return result;
}
});
View v = navigationView.getHeaderView(0);
TextView t = (TextView)v.findViewById(R.id.username);
t.setText(username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.log_out, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.log_out:
logoutUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(Welcome.this, MainActivity.class);
startActivity(intent);
finish();
}
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
WelcomeFragment welcomeFragment = new WelcomeFragment();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction fragmentTra1 = fm1.beginTransaction();
fragmentTra1.replace(R.id.content,welcomeFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra1.commit();
return true;
case R.id.general:
GeneralFragment generalFragment= new GeneralFragment();
FragmentManager fm2 = getSupportFragmentManager();
FragmentTransaction fragmentTra2 = fm2.beginTransaction();
fragmentTra2.replace(R.id.content,generalFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra2.commit();
return true;
case R.id.announcements:
AnnouncementsFragment announcementsFragment= new AnnouncementsFragment();
FragmentManager fm3 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubOne = fm3.beginTransaction();
fragmentTraSubOne.replace(R.id.content,announcementsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubOne.commit();
return true;
case R.id.sub_one:
NewsFragment newsFragment= new NewsFragment();
FragmentManager fm4 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubTwo = fm4.beginTransaction();
fragmentTraSubTwo.replace(R.id.content,newsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubTwo.commit();
return true;
case R.id.sub_two:
FanClubFragment fanClubFragment= new FanClubFragment();
FragmentManager fm5 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubThree = fm5.beginTransaction();
fragmentTraSubThree.replace(R.id.content,fanClubFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubThree.commit();
return true;
}
return false;
}
public static Intent newIntent(Context context) {
return new Intent(context,MainActivity.class);
}
#Override
public void onBackPressed() {
if(isNavDrawerOpen()){
closeDrawerLayout();
}else {
super.onBackPressed();
}
}
public boolean isNavDrawerOpen() {
return drawerLayout!=null && drawerLayout.isDrawerOpen(GravityCompat.START);
}
private void closeDrawerLayout(){
if(drawerLayout != null){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return (keyCode == KeyEvent.KEYCODE_BACK ? true :
super.onKeyDown(keyCode, event));
}
}
Any ideas?
Thanks,
Theo.
Try using setTitle():
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
toolbar.setTitle("Welcome");
......
}
.....
}
Try using:
getSupportActionBar().setTitle("title");
in the switch-case
I think you could use something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Also this link might help: Here
Hope it helps ;)
btw your app looks great!
I am new to Android development and I don't have too much SO coins.
Basically, my project has a main screen activity and it contains 3 tabs, which are MyGiftsFragment, FriendsGiftsFragment and AboutMeFragment. I implemented tablayout and viewpager here. The problem is when I sign in the app, the first page(MyGiftsFragment) is empty, not loading anything(sometimes it loaded.) But when I swiped to the last tab(AboutMeFragment) and come back to the first tab, the content will be loaded. And this only works when I swiped to the last tab.
Due to my limit English, I am not sure if I explain the question clear. If you need any further information, please comment. I've searched the "setUserVisibleHint" and "setOnPageChangeListener(pageChangeListener)", but it seems that they are not what I want. Any advice will be appreciated. Thank you so much.
Here are my MainScreenActivity code.
public class MainScreenActivity extends AppCompatActivity {
private static final String TAG = MainScreenActivity.class.getName();
FirebaseAuth mAuth;
private DrawerLayout mDrawerLayout;
private FloatingActionButton fab;
private ArrayList<Gift> mGiftArray;
private RecyclerView mRecyclerView;
private boolean doubleBackToExitPressedOnce = false;
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplication().getApplicationContext());
mAuth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_main_screen);
/** Setup Toolbar and ActionBar. */
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
/** Setup DrawerLayout. */
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
/** 1.Setup drawer header content: Title and profile picture. */
View drawerHeader = navigationView.getHeaderView(0);
NetworkImageView drawerPicture = (NetworkImageView) drawerHeader.findViewById(R.id.drawer_picture);
NetworkImageView coverPicture = (NetworkImageView) drawerHeader.findViewById(R.id.cover_picture);
/** Fetch data from SharePreferences. */
SharedPreferences mSharedPreferences = this.getSharedPreferences("test", Activity.MODE_PRIVATE);
String drawerPictureUrl = mSharedPreferences.getString("picture", "");
String coverPictureUrl = mSharedPreferences.getString("cover", "");
ImageLoader imageLoader = MySingleton.getInstance(MainScreenActivity.this.getApplicationContext()).getImageLoader();
drawerPicture.setImageUrl(drawerPictureUrl, imageLoader);
coverPicture.setImageUrl(coverPictureUrl, imageLoader);
/** 2.Setup drawer body content: Name, E-mail and birthday. */
/** Fetch data from SharePreferences. */
String username = mSharedPreferences.getString("username", "");
String email = mSharedPreferences.getString("email", "");
String birthday = mSharedPreferences.getString("birthday", "");
Menu menu = navigationView.getMenu();
MenuItem nav_name = menu.findItem(R.id.navigation_item_name);
nav_name.setTitle(username);
MenuItem nav_email = menu.findItem(R.id.navigation_item_email);
nav_email.setTitle(email);
MenuItem nav_birthday = menu.findItem(R.id.navigation_item_birthday);
nav_birthday.setTitle(birthday);
/** Setup item onSelectedListener. */
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Intent intent;
if (menuItem.getItemId() == R.id.navigation_item_name) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_email) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_birthday) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_payment) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_refresh) {
mDrawerLayout.closeDrawers();
finish();
startActivity(getIntent());
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_logout) {
mDrawerLayout.closeDrawers();
facebookLogout();
return true;
}
return false;
}
});
/** Setup FloatingActionButton. */
fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, AddGiftsActivity.class);
context.startActivity(intent);
}
});
TabPagerAdapter adapter = new TabPagerAdapter(this, getSupportFragmentManager());
final ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
animateFab(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//
// viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// #Override
// public void onPageSelected(int position) {
// // do your work
// }
// });
}
private void animateFab(int position) {
switch (position) {
case 0:
fab.show();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, AddGiftsActivity.class);
context.startActivity(intent);
}
});
break;
case 1:
fab.show();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, AddGiftsActivity.class);
context.startActivity(intent);
}
});
break;
default:
fab.hide();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_settings:
return true;
case R.id.action_logout:
facebookLogout();
}
return super.onOptionsItemSelected(item);
}
static class TabPagerAdapter extends FragmentStatePagerAdapter {
private Context mContext;
public TabPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public Fragment getItem(int position) {
if (position == 0) {
return new MyGiftsFragment();
} else if (position == 1) {
return new FriendsGiftsFragment();
} else {
return new AboutMeFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return mContext.getString(R.string.my_gifts);
} else if (position == 1) {
return mContext.getString(R.string.friends_gifts);
} else {
return mContext.getString(R.string.about_me);
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void facebookLogout() {
if (mAuth.getCurrentUser() != null) {
Log.e("22", "Not sign out yet.");
} else {
Log.e("22", "Signed out already.");
}
mAuth.signOut();
if (mAuth.getCurrentUser() != null) {
Log.e("22", "Not sign out yet.");
} else {
Log.e("22", "Signed out already.");
}
LoginManager.getInstance().logOut();
Log.e("facebook", "logout");
startActivity(new Intent(MainScreenActivity.this, FacebookLoginActivity.class));
finish();
}
}
And here is MyGiftsFragment
public class MyGiftsFragment extends Fragment {
private static final String TAG = MyGiftsFragment.class.getName();
private ArrayList<Gift> mGiftArray;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private DatabaseReference mDatabase;
private String facebookId;
public MyGiftsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mGiftArray = new ArrayList<>();
SharedPreferences mSharedPreferences = this.getActivity().getSharedPreferences("test", Activity.MODE_PRIVATE);
facebookId = mSharedPreferences.getString("facebookId", "");
mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference myWishList = mDatabase.child("user/" + facebookId + "/my_gift/" + "/wish_list");
myWishList.addChildEventListener(new ChildEventListener() {
/** Add new gift */
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mGiftArray.clear();
/** com.jluo80.amazinggifter.MyGiftsFragment:-KMa77KnGU5hsF8dngVc*/
final String uniqueKey = dataSnapshot.getKey();
Log.e(TAG, "onChildAdded:" + uniqueKey);
/** com.jluo80.amazinggifter.MyGiftsFragment:true */
Log.e(TAG, "onChildAdded:" + dataSnapshot.getValue());
DatabaseReference ref = mDatabase.child("gift").child(uniqueKey);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot item) {
Log.e(TAG, "Single" + item.getKey());
System.out.println("test" + item.getValue());
Gift gift = item.getValue(Gift.class);
gift.setUnique_key(uniqueKey);
System.out.println(gift.getInitiator_id() + "&&&&&&&" + gift.getReceiver_id());
String end = gift.getDue_date();
String start = getCurrentDate();
if(gift.getProgress() <= gift.getPrice() && end.compareTo(start) >= 0) {
mGiftArray.add(gift);
mRecyclerView.setAdapter(new MyGiftRecyclerAdapter(getContext(), mGiftArray));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
}
});
DatabaseReference fromFriendsList = mDatabase.child("user/" + facebookId + "/my_gift/" + "/from_friends");
fromFriendsList.addChildEventListener(new ChildEventListener() {
/** Add new gift */
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// mGiftArray.clear();
/** com.jluo80.amazinggifter.MyGiftsFragment:-KMa77KnGU5hsF8dngVc*/
final String uniqueKey = dataSnapshot.getKey();
Log.e(TAG, "onChildAdded:" + uniqueKey);
/** com.jluo80.amazinggifter.MyGiftsFragment:true */
Log.e(TAG, "onChildAdded:" + dataSnapshot.getValue());
DatabaseReference ref = mDatabase.child("gift/" + uniqueKey);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot item) {
Log.e(TAG, "Single" + item.getKey());
System.out.println("test" + item.getValue());
Gift gift = item.getValue(Gift.class);
gift.setUnique_key(uniqueKey);
System.out.println(gift.getInitiator_id() + "&&&&&&&" + gift.getReceiver_id());
String end = gift.getDue_date();
String start = getCurrentDate();
if(gift.getProgress() <= gift.getPrice() && end.compareTo(start) >= 0) {
mGiftArray.add(gift);
mRecyclerView.setAdapter(new MyGiftRecyclerAdapter(getContext(), mGiftArray));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
}
});
return rootView;
}
public String getCurrentDate() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("MM/dd/yy");
return mdformat.format(calendar.getTime());
}
}
Please add this line before setting adapter. This will fix the issue
viewPager.setOffscreenPageLimit(3);
Offscreen page limit will decide how many adjacent pages need to be loaded when you see a page. So in your case set it to 3 (all pages).
Then your code will change to,
final ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3); //Add this
viewPager.setCurrentItem(0);
Good luck!