How to show data from a db in 3 tabbed Fragments?

Asked

Viewed 228 times

0

How to show the data obtained from a database in a tab with 3 Fragments. I can already get the data from the tab in Activity. My difficulty is in throwing this dice on controls that are arranged in the 3 Fragment.

Mainactivity

public class MainActivity extends AppCompatActivity {


private SectionsPagerAdapter mSectionsPagerAdapter;


private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());


    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));


    Button b= (Button) findViewById(R.id.btnClick);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Frag1 f1= new Frag1();
            Bundle bundle = new Bundle();
            bundle.putString("name", "Marcelo");
            f1.setArguments(bundle);


        }
    });



}



public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment=null;
        switch (position){

            case 0:
                fragment=  new Frag1();
                break;

            case 1:
                fragment= new Frag2();
                break;

            case 2:
                fragment= new Frag3();
                break;
        }

        return fragment;
    }

    @Override
    public int getCount() {

        return 3;
    }

}

Fragment

public class Frag1 extends Fragment {
public TextView t1;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.frag1_layout, container, false);
    t1 = (TextView) v.findViewById(R.id.txtFinal1);


    return v;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Bundle bundle = getArguments();



    if (bundle != null)
    {

        String link = bundle.getString("name");
        t1.setText(link);

    }
    else{Log.d("TagStart","Nulo");}

}

The Activity button sends the data to show in the Textview of Fragment but nothing happens. Nemhum error also happens.

  • 1

    Welcome to the Stackoverflow. Please post an excerpt of the code you already have to get a better idea of the problem, I suggest you read this help article from the site: How to create a Minimum, Complete and Verifiable example.

  • Thanks for the tip Pedro Gaspar. I’m new here I’ve posted with the code snippet.

2 answers

1


Solved. In this example I take the data of an Azure DB and distribute in 2 tabbed Fragments. One with the personal data and the other with an edge.

Mainactivity

public class MainActivity extends AppCompatActivity  {

private MobileServiceClient mClient;
private MobileServiceTable<cadastroTable> mCadastroTable;
private CadastroTableAdapter mCadastroAdapter;
private Toolbar mToolbar;
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
private String codigo,nome,endereco,bairro,cidade,estado;
private ArrayAdapter<String> listAdapter;
private TabLayout tabLayout;
public  Bundle bundle = new Bundle();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_people);


    mToolbar = (Toolbar) findViewById(R.id.tb_main);
    mToolbar.setTitle("");
    setSupportActionBar(mToolbar);


    try {

        mClient = new MobileServiceClient(
                "https://contaazure.azurewebsites.net",
                this));


        mClient.setAndroidHttpClientFactory(new OkHttpClientFactory() {
            @Override
            public OkHttpClient createOkHttpClient() {
                OkHttpClient client = new OkHttpClient();
                client.setReadTimeout(20, TimeUnit.SECONDS);
                client.setWriteTimeout(20, TimeUnit.SECONDS);
                return client;
            }
        });


        mCadastroTable = mClient.getTable(cadastroTable.class);



        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.stl_tabs);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

        mSectionsPagerAdapter.getItem(0);


    } catch (MalformedURLException e) {
        createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
    } catch (Exception e) {
        createAndShowDialog(e, "Error");
    }


    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


}




public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
    }

    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        android.support.v4.app.Fragment fragment=null;


        switch (position){

            case 0:
                fragment=  new PessoalFragment();
                Bundle bundle = new Bundle();
                bundle.putString("nome",nome);
                bundle.putString("codigo",codigo);

                fragment.setArguments(bundle);

                break;

            case 1:
                fragment= new LocalizacaoFragment();
                Bundle bundle1 = new Bundle();
                bundle1.putString("endereco",endereco);
                bundle1.putString("bairro",bairro);
                bundle1.putString("cidade",cidade);
                bundle1.putString("estado",estado);

                fragment.setArguments(bundle1);

                break;


        }

        return fragment;
    }

    @Override
    public int getCount() {

        return 2;
    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
  //  getMenuInflater().inflate(R.menu.home, menu);
    return true;
}





public  void refreshCadastroTable() {

      /// Aqui eu pego no DB do Azure os campos que serão que vão nas
      /// variáveis do bundle

}




private void createAndShowDialogFromTask(final Exception exception, String title) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            createAndShowDialog(exception, "Error");
        }
    });
}


private void createAndShowDialog(Exception exception, String title) {
    Throwable ex = exception;
    if(exception.getCause() != null){
        ex = exception.getCause();
    }
    createAndShowDialog(ex.getMessage(), title);
}




private void createAndShowDialog(final String message, final String title) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage(message);
    builder.setTitle(title);
    builder.create().show();
}

In the Factions

Personal

public class PessoalFragment extends Fragment  {

private EditText edt_cdigo, edt_nome;
public  String _codigo, _nome, ;
public Bundle bundle;


@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_pessoal, container, false);

     edt_codigo = (EdiText) getActivity().findViewById(R.id.codigo);
     edt_nome = (EditText) view.findViewById(R.id.nome);


    return view;
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);

    bundle= getArguments();

    _codigo = bundle.getString("codigo");
    _nome = bundle.getString("nome");


}



@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);



    if (bundle != null) {

        edt_codigo.setText(_codigo);
        edt_nome.setText(_nome);

    }


}

Localizacaofragment

public class LocalizacaoFragment extends Fragment  {

private EditText edt_endereco, edt_bairro, edt_cidade, edt_estado;
public  String _endereco, _bairro, _cidade, _estado ;
public Bundle bundle;


@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_localizacao, container, false);

     edt_endereco = (EdiText) getActivity().findViewById(R.id.endereco);
     edt_bairro = (EditText) view.findViewById(R.id.bairro);
     edt_cidade = (EdiText) getActivity().findViewById(R.id.cidade);
     edt_estado = (EditText) view.findViewById(R.id.estado);


    return view;
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);

    bundle= getArguments();

    _endereco = bundle.getString("endereco");
    _bairro = bundle.getString("bairro");
    _cidade = bundle.getString("cidade");
    _estado = bundle.getString("estado");


}



@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);



    if (bundle != null) {

        edt_endereco.setText(_endereco);
        edt_bairro.setText(_bairro);
        edt_cidade.setText(_cidade);
        edt_estado.setText(_estado);

    }


}

Thanks Lucas Pugliese for the help.

0

Oh Sectionspagerapter has a Frag1, but at no time do you assign the Bundle to it. You are actually creating a Frag1 new within the Onclick button.

Another thing you have to note is the life cycle of Activity and Fragment, because the click of the button is happening after the onActivityCreated and at that time the Bundle will always be null

Ciclo de vida da activity e fragment

In your specific case I believe the best approach would be for you to create a method SetText() in his Fragment, create a GetFragment() within the Adapter to access the same from Activity and simply call the SetText() within the OnClick.

  • 1

    Thanks!!! That’s what it was.. Oh Sectionspagera has a Frag1, but in no time you assign the Bundle to it. Rookie mistake like me.

  • Posted as was the final result and vote in response. Thank you for giving feedback ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.