0
I’ve seen some posts about but I couldn’t figure out how to pass a string from one activity
for a fragment
I got the main:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
SearchView.OnQueryTextListener {
private Fragment currentFragment;
private home fragment1 = new home();
private clientes fragment2 = new clientes();
private contas_pagar fragment3 = new contas_pagar();
private contas fragment4 = new contas();
String t = "teste";
private BottomViewPagerAdapter bottomViewPagerAdapter;
private ArrayList<AHBottomNavigationItem> bottomNavigationItems = new
ArrayList<>();
// UI
private AHBottomNavigationViewPager viewPagerBottom;
private AHBottomNavigation bottomNavigation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clientes apresentacaofragment = new clientes();
// Declarando o valor
Bundle bundlemain = new Bundle();
bundlemain.putString("TESTE1", "olá");
// Passando os dados
apresentacaofragment.setArguments(bundlemain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
initUI();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView)
MenuItemCompat.getActionView(searchItem);
// Configure the search info and add any event listeners
return super.onCreateOptionsMenu(menu);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void initUI() {
bottomNavigation = (AHBottomNavigation)
findViewById(R.id.bottom_navigation);
viewPagerBottom = (AHBottomNavigationViewPager)
findViewById(R.id.view_pager_bottom);
//Aqui onde é adicionado os fragments no bottom
viewPagerBottom.setOffscreenPageLimit(2);
bottomViewPagerAdapter = new
BottomViewPagerAdapter(getSupportFragmentManager());
bottomViewPagerAdapter.add(fragment1);
bottomViewPagerAdapter.add(fragment2);
bottomViewPagerAdapter.add(fragment3);
bottomViewPagerAdapter.add(fragment4);
viewPagerBottom.setAdapter(bottomViewPagerAdapter);
currentFragment = bottomViewPagerAdapter.getCurrentFragment();
AHBottomNavigationItem item1 = new AHBottomNavigationItem("Home",
R.drawable.ic_home_black_24dp);
AHBottomNavigationItem item2 = new AHBottomNavigationItem("Clientes",
R.drawable.clientes);
AHBottomNavigationItem item3 = new AHBottomNavigationItem("Contas",
R.drawable.pagar);
AHBottomNavigationItem item4 = new AHBottomNavigationItem("Histórico",
R.drawable.contas);
bottomNavigationItems.add(item1);
bottomNavigationItems.add(item2);
bottomNavigationItems.add(item3);
bottomNavigationItems.add(item4);
bottomNavigation.addItems(bottomNavigationItems);
bottomNavigation.setAccentColor(Color.parseColor("#F63D2B"));
bottomNavigation.setInactiveColor(Color.parseColor("#747474"));
bottomNavigation.setCurrentItem(0);
bottomNavigation.setNotification("Vencida", 2);
bottomNavigation.findViewById(R.id.textView18);
bottomNavigation.setOnTabSelectedListener(new
AHBottomNavigation.OnTabSelectedListener() {
@Override
public boolean onTabSelected(int position, boolean wasSelected) {
if (currentFragment == null) {
currentFragment =
bottomViewPagerAdapter.getCurrentFragment();
}
if (currentFragment != null) {
if (currentFragment instanceof home) {
fragment1.willBeHidden();
} else if (currentFragment instanceof clientes) {
fragment2.willBeHidden();
} else if (currentFragment instanceof contas_pagar) {
fragment3.willBeHidden();
} else if (currentFragment instanceof contas){
fragment4.willBeHidden();
}
}
//Aqui é onde é setado qual o fragment atual
//Em seguida é pego o fragment atual e feito o fade dependendo
de qual instancia for
viewPagerBottom.setCurrentItem(position, false);
currentFragment = bottomViewPagerAdapter.getCurrentFragment();
if (currentFragment instanceof home) {
fragment1.willBeDisplayed();
} else if (currentFragment instanceof clientes) {
fragment2.willBeDisplayed();
} else if (currentFragment instanceof contas_pagar) {
fragment3.willBeDisplayed();
} else if (currentFragment instanceof contas){
fragment4.willBeDisplayed();
}
if (position == 0) {
}
return true;
}
});
bottomNavigation.setOnNavigationPositionListener(new
AHBottomNavigation.OnNavigationPositionListener() {
@Override
public void onPositionChange(int y) {
Log.d("DemoActivity", "BottomNavigation Position: " + y);
}
});
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
I tried to pass the data like this:
clientes apresentacaofragment = new clientes();
// Declarando o valor
Bundle bundlemain = new Bundle();
bundlemain.putString("TESTE1", "olá");
// Passando os dados
apresentacaofragment.setArguments(bundlemain);
And receive so in Fragment
Bundle dados = getArguments();
String valor = dados.getString("TESTE1");
code of Fragment:
public class clientes extends Fragment {
private FrameLayout fragmentContainer;
private FloatingActionButton addCli, refresh;
private ListView lista;
public ProgressBar progressBar;
String url = "";
String parametros = "";
String[] array = new String[8];
String[] nome = {};
String[] telefone = {};
String[] celular = {};
String[] renda = {};
String[] limite = {};
String[] status = {};
String[] bandeira = {};
String[] id2 = {};
String select, nome2, telefone2, celular2, renda2, limite2, status2,
bandeira2, texto;
String id123;
String teste;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_clientes, container,
false);
Bundle dados = getArguments();
String valor = dados.getString("TESTE1");
setHasOptionsMenu(true);
fragmentContainer = (FrameLayout)
view.findViewById(R.id.fragment_container_1);
addCli = (FloatingActionButton)
view.findViewById(R.id.floatingActionButton);
refresh = (FloatingActionButton) view.findViewById(R.id.refresh);
progressBar = (ProgressBar) view.findViewById(R.id.login_progress);
TextView teste2 = (TextView) view.findViewById(R.id.textView18);
Toast.makeText(getActivity().getApplicationContext(), valor,
Toast.LENGTH_SHORT).show();
Intent intent = getActivity().getIntent();
id123 = intent.getStringExtra("id");
lista = (ListView) view.findViewById(R.id.pagar);
addCli.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), new_cliente.class);
intent.putExtra("id123", id123);
startActivity(intent);
}
});
refresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listartodos();
}
});
listartodos();
return view;
}
Bottomviewpageradapter:
public class BottomViewPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragments = new ArrayList<>();
private Fragment currentFragment;
public BottomViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void add(Fragment frag) {
this.fragments.add(frag);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
if (getCurrentFragment() != object) {
currentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
/**
* Get the current fragment
*/
public Fragment getCurrentFragment() {
return currentFragment;
}
}
logcat:
02-09 13:38:54.015 11299-11299/insidetechnology.studio.ostdor.forbusiness E/Androidruntime: FATAL EXCEPTION: main Process: insidetechnology.studio.ostdor.forbusiness, PID: 11299 java.lang.Nullpointerexception: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null Object Reference at insidetechnology.studio.ostdor.forbusiness..onCreateView(home.java:61) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2248) at android.support.v4.app.Fragmentmanagerimpl.moveToState(Fragmentmanager.java:1340) at android.support.v4.app.Fragmentmanagerimpl.moveFragmentToExpectedState(Fragmentmanager.java:1569) at android.support.v4.app.Fragmentmanagerimpl.moveToState(Fragmentmanager.java:1636) at android.support.v4.app.Backstackrecord.executeOps(Backstackrecord.java:758) at android.support.v4.app.Fragmentmanagerimpl.executeOps(Fragmentmanager.java:2415) at android.support.v4.app.Fragmentmanagerimpl.executeOpsTogether(Fragmentmanager.java:2201) at android.support.v4.app.Fragmentmanagerimpl.optimizeAndExecuteOps(Fragmentmanager.java:2155) at android.support.v4.app.Fragmentmanagerimpl.execSingleAction(Fragmentmanager.java:2034) at android.support.v4.app.Backstackrecord.commitNowAllowingStateLoss(Backstackrecord.java:626) at android.support.v4.app.Fragmentpageradapter.finishUpdate(Fragmentpageradapter.java:143) at android.support.v4.view.Viewpager.populate(Viewpager.java:1268) at android.support.v4.view.Viewpager.populate(Viewpager.java:1116) at android.support.v4.view.Viewpager.onMeasure(Viewpager.java:1642) at android.view.View.Measure(View.java:20084) at android.view.Viewgroup.measureChildWithMargins(Viewgroup.java:6282) at android.support.design.widget.Coordinatorlayout.onMeasureChild(Coordinatorlayout.java:714) at android.support.design.widget.Coordinatorlayout.onMeasure(Coordinatorlayout.java:786) at android.view.View.Measure(View.java:20084) at android.support.v4.widget.Drawerlayout.onMeasure(Drawerlayout.java:1081) at android.view.View.Measure(View.java:20084) at android.view.Viewgroup.measureChildWithMargins(Viewgroup.java:6282) at android.widget.Framelayout.onMeasure(Framelayout.java:214) at android.support.v7.widget.Contentframelayout.onMeasure(Contentframelayout.java:139) at android.view.View.Measure(View.java:20084) at android.view.Viewgroup.measureChildWithMargins(Viewgroup.java:6282) at android.widget.Linearlayout.measureChildBeforeLayout(Linearlayout.java:1705) at android.widget.Linearlayout.measureVertical(Linearlayout.java:797) at android.widget.Linearlayout.onMeasure(Linearlayout.java:657) at android.view.View.Measure(View.java:20084) at android.view.Viewgroup.measureChildWithMargins(Viewgroup.java:6282) at android.widget.Framelayout.onMeasure(Framelayout.java:214) at android.view.View.Measure(View.java:20084) at android.view.Viewgroup.measureChildWithMargins(Viewgroup.java:6282) at android.widget.Linearlayout.measureChildBeforeLayout(Linearlayout.java:1705) at android.widget.Linearlayout.measureVertical(Linearlayout.java:797) at android.widget.Linearlayout.onMeasure(Linearlayout.java:657) )
Does anyone know how to pass the string between Activity and Fragment?
Please do not mark as duplicate because the other question similar to this does not explain virtually anything.
What is it that you don’t understand? Where your code doesn’t work?
– ramaral
The way I showed it, it doesn’t work, just when I open the app
– Woton Sampaio
If it stops working it is because it was wrong. See in the tab logcat what is it and put it in question.
– ramaral
How do I see this tab? I have to open it by emulator?
– Woton Sampaio
@ready ramaral, added
– Woton Sampaio
The error is in the file/fragment
home.java
– Valdeir Psr
@Valdeirpsr and how do I fix it? Would N have another method of passing data between Activity and Fragments not? If yes, you could show me something?
– Woton Sampaio
@Wotonsampaio the way you are doing is not wrong, but the mistake is because you are not passing the
Bundle
to the fragmenthome
. What is the code of the fragmenthome
. In the methodgetItem
ofBottomViewPagerAdapter
the arguments must be set. Sample code https://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html– Valdeir Psr
@Valdeirpsr the fragment code I included in the question, I’ll take a look at your example there.
– Woton Sampaio