I have FAB and TabLayout with viewpager in mainAcitivty. I want to update fragment of viewpager when user provide input by FAB. Trying to send data via Bundle but always Bundle is null while receiving from fragment.
I think my problem is in receiving data. To which fragment method I should use to receive data?
Here is my MainActivity
package com.example.shahalam.rvfabvptl;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText title, description;
FloatingActionButton fab;
ViewPager mPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_box,null);
title = mView.findViewById(R.id.titleDialogBox);
description = mView.findViewById(R.id.descriptionDialogBox);
Button btnOK = mView.findViewById(R.id.btnOk);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
final FragmentOne fragOne = new FragmentOne();
Bundle mBundle = new Bundle();
mBundle.putString("title", title.getText().toString());
mBundle.putString("description", description.getText().toString());
//PASS OVER THE BUNDLE TO OUR FRAGMENT
FragmentOne myFragment = new FragmentOne();
myFragment.setArguments(mBundle);
ft.add(R.id.linearLayoutFragmentOne,fragOne);
ft.commit();
dialog.cancel();
}
});
}
});
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(mPager);
}
}
And here is my Fragment class:
package com.example.shahalam.rvfabvptl;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class FragmentOne extends Fragment {
public FragmentOne() {
}
RecyclerView fragOneRecyclerView;
List<MyDataModel> myDataModels = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one,container,false);
fragOneRecyclerView = view.findViewById(R.id.fragmentOneRecyclerView);
fragOneRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final RecyclerViewAdapter adapterFragmentOne = new RecyclerViewAdapter(getContext(),myDataModels);
fragOneRecyclerView.setAdapter(adapterFragmentOne);
Bundle mBundle =getArguments();
String title="if Bundle is null", description="No description";
if (mBundle != null) {
title = this.getArguments().getString("title");
description = this.getArguments().getString("description");
}
MyDataModel mOne4 = new MyDataModel(title,description);
myDataModels.add(mOne4);
adapterFragmentOne.notifyDataSetChanged();
return view;
}
}
You are creating two different objects of your Fragment FragmentOne ,
and setting the bundle to object myFragment and passing another fragment object fragOne in FragmentTransition. which is wrong , use
the below code.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentOne fragOne = new FragmentOne();
Bundle mBundle = new Bundle();
mBundle.putString("title", title.getText().toString());
mBundle.putString("description", description.getText().toString());
//PASS OVER THE BUNDLE TO OUR FRAGMENT
fragOne.setArguments(mBundle);
ft.add(R.id.linearLayoutFragmentOne,fragOne);
ft.commit();
dialog.cancel();
Related
I am making my first app using Firebase. I am unable to fetch data from Firebase in Android Studio but I was able to upload it using login and sign up features which I created in my app.
Whenever I run the app, it does not show any error but app automatically closes after the splash screen. I am unable to resolve this error.
MainActivity.java
package com.example.blooddonationapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private NavigationView nav_view;
private CircleImageView nav_profile_image;
private TextView nav_fullname, nav_email, nav_bloodgroup, nav_type;
private DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Blood Donation App");
drawerLayout = findViewById(R.id.drawerLayout);
nav_view = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
nav_view.setNavigationItemSelectedListener(this);
nav_profile_image = nav_view.getHeaderView(0).findViewById(R.id.nav_user_image);
nav_fullname = nav_view.getHeaderView(0).findViewById(R.id.nav_user_fullname);
nav_email = nav_view.getHeaderView(0).findViewById(R.id.nav_user_email);
nav_bloodgroup = nav_view.getHeaderView(0).findViewById(R.id.nav_user_bloodgroup);
nav_type = nav_view.getHeaderView(0).findViewById(R.id.nav_user_type);
userRef = FirebaseDatabase.getInstance().getReference().child("users").child(
FirebaseAuth.getInstance().getCurrentUser().getUid()
);
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String name = snapshot.child("name").getValue().toString();
nav_fullname.setText(name);
String email = snapshot.child("email").getValue().toString();
nav_email.setText(email);
String bloodgroup = snapshot.child("bloodgroup").getValue().toString();
nav_bloodgroup.setText(bloodgroup);
String type = snapshot.child("type").getValue().toString();
nav_type.setText(type);
String imageUrl = snapshot.child("profilepictureurl").getValue().toString();
Glide.with(getApplicationContext()).load(imageUrl).into(nav_profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.profile:
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
ProfileActivity.java
package com.example.blooddonationapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileActivity extends AppCompatActivity {
private Toolbar toolbar;
private TextView type, name, email, idNumber, phoneNumber, bloodGroup;
private CircleImageView profileImage;
private Button backButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("My Profile");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
type = findViewById(R.id.type);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
idNumber = findViewById(R.id.idNumber);
phoneNumber = findViewById(R.id.phoneNumber);
bloodGroup = findViewById(R.id.bloodGroup);
profileImage = findViewById(R.id.profileImage);
backButton = findViewById(R.id.backButton);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
type.setText(snapshot.child("type").getValue().toString());
name.setText(snapshot.child("name").getValue().toString());
idNumber.setText(snapshot.child("idnumber").getValue().toString());
phoneNumber.setText(snapshot.child("phonenumber").getValue().toString());
bloodGroup.setText(snapshot.child("bloodgroup").getValue().toString());
email.setText(snapshot.child("email").getValue().toString());
Glide.with(getApplicationContext()).load(snapshot.child("profilepictureurl").getValue().toString()).into(profileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Firebase
LogCat
this code was working perfectly when i was using navigation drawer activity after making some changes to my project and start using bottom navigation activity it just wont work and give my the error of incompatible types .. i tried every possible answer related to this issue but i get the same error
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity {
private TextView mTextMessage;
SearchFragment searchFragment;
private FrameLayout Eframe;
private HomeFragment homeFragment;
private BottomNavigationView eNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Eframe = findViewById(R.id.main_frame);
searchFragment = new SearchFragment();
setFragment(searchFragment);
eNav = findViewById(R.id.Nav);
eNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Search:
> setFragment(searchFragment);
return true;
case R.id.Home:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.Profile:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Menu:
mTextMessage.setText(R.string.title_notifications);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
}
}
instead of extends AppCompatActivity
write extends Fragment.
I am using the default Navigation Drawer in android studio and I have a dynamically created fragment and use TabLayout to run it. It will run normally but as I try to load the same fragment from the navigation drawer i run into error. Please see below:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Introduction extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final RelativeLayout relativeLayout = new RelativeLayout(getActivity());
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
relativeLayout.setLayoutParams(layoutParams);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
final ImageView introImage = new ImageView(getActivity());
introImage.setId(R.id.introImageId);
introImage.setImageResource(R.drawable.introduction);
introImage.setAnimation(AnimationUtils.loadAnimation(this.getContext(), android.R.anim.slide_out_right));
introImage.setPadding(100, 100, 100, 100);
final TextView introText = new TextView(getActivity());
introText.setText(R.string.introduction_text);
// introText.setTextAppearance(android.R.style.TextAppearance_Medium);
introText.setTextSize(20);
introText.setPadding(25,25,25,25);
introText.setTextColor(ContextCompat.getColor(this.getContext(), R.color.colorPrimary));
params.addRule(RelativeLayout.BELOW, introImage.getId());
introText.setAnimation(AnimationUtils.loadAnimation(this.getContext(),android.R.anim.slide_in_left));
relativeLayout.addView(introText,params);
relativeLayout.addView(introImage);
return relativeLayout;
}
}
But as I try to load it from Navigation drawer I get an error Error:(115, 62) error: incompatible types: Introduction cannot be converted to Fragment
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fn = getFragmentManager();
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_introduction) {
fn.beginTransaction().replace(R.id.content_frame,new Introduction()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
TabPagerAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter {
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount=numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Introduction tab1= new Introduction();
return tab1;
default:
return null;
}
}
I replaced getFragmentManager(); with getSupportFragmentManager(); and its working
// FragmentManager fn = getFragmentManager();
FragmentManager fn = getSupportFragmentManager();
I'm Implementing Flipboard Animation in my activity pageIndicatorActivity its showing an error i.e The method Page(NoteViewAdapter) in the type FlipViewController is not applicable for the arguments
(PageIndicatorActivity.NoteViewAdapter)
this is the error I'm facing
here is my code
package com.horizontalscrollviewwithpageindicator;
import java.util.ArrayList;
import com.aphidmobile.flip.FlipViewController;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class PageIndicatorActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
ArrayList<String> notes = new ArrayList<String>();
notes.add("Come");
notes.add("On");
notes.add("Flip");
notes.add("Me");
//You can also use FlipViewController.VERTICAL
FlipViewController flipView = new FlipViewController(this, FlipViewController.HORIZONTAL);
//We're creating a NoteViewAdapter instance, by passing in the current context and the
//values to display after each flip
flipView.Page(new NoteViewAdapter(this, notes));
setContentView(flipView);
}
public abstract class NoteViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<String> notes;
public NoteViewAdapter(Context currentContext, ArrayList<String> allNotes) {
inflater = LayoutInflater.from(currentContext);
notes = allNotes;
}
#Override
public int getCount() {
return notes.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout = convertView;
if (convertView == null) {
layout = inflater.inflate(R.layout.activity_main, null);
}
//Get's value from our ArrayList by the position
String note = notes.get(position);
TextView tView = (TextView) layout.findViewById(R.id.note);
tView.setText(note);
return layout;
}
}
private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
R.drawable.antartica3, R.drawable.antartica4,
R.drawable.antartica5, R.drawable.antartica6,
R.drawable.antartica7, R.drawable.antartica8 };
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
App need to open some websites when i touch buttons. There are 2 tabs (2 fragments) with different buttons (1 button = 1 link)
When i click a Button that need to open WebView (to open a link) application crash. I think, mistake is somewhere in AFragment.java
main.java (it's good 99,9%)
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
public static Context appContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab PTab = actionbar.newTab().setText("One");
ActionBar.Tab DTab = actionbar.newTab().setText("Two");
Fragment OneFragment = new AFragment();
Fragment TwpFragment = new BFragment();
PTab.setTabListener(new MyTabsListener(OneFragment));
DTab.setTabListener(new MyTabsListener(TwoFragment));
actionbar.addTab(PTab);
actionbar.addTab(DTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
//Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
AFragment.java:
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class AFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
SavedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.afragment, container, false);
}
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
}
openPage.class:
import android.webkit.WebView;
import android.app.Activity;
import android.os.Bundle;
public class openPage extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://safhkalfsd.com");
}
}
Layouts are fine 99,99%
i put
android:onClick="openIt"
in afragment.xml inside Button
THANK YOU
SOLVED!
I need to put:
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
in MainActivity, not in 'AFragment'.