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

0

How to display the data obtained from a database in a tab with 3 fragments. I already get the data in the activity that is on the tab. My difficulty lies in playing this data 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 the fragment but nothing happens. There is no such thing as an error.

    
asked by anonymous 19.10.2018 / 07:09

2 answers

1

Resolved . In this example I get the data from an Azure DB and distribute it in 2 tabbed fragments. One with personal data and the other with address.

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 fragments

PersonalFragment

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);

    }


}

LocationFragment

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);

    }


}

Thank you Lucas Pugliese for the help.

    
24.10.2018 / 22:19
0

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

Another thing you have to note is the activity and fragment lifecycle because the button click is happening after onActivityCreated and at that time the Bundle > will always be null

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

    
22.10.2018 / 16:25