My problem is that I can't update the data of my AcTview adapter, when I enter data from another of my fragment.
In PageAdjuFragment I have the ACTV tv2 and his adapter adapter2.
The data of this adapter are created by getListpart() in VenteFragment (PageAdjuFragment extends VenteFragment).
I know that getListpart() and initpart() work cause when I relaunch my app, the new data appears in my actv.
I think that the problem is when I switching between my fragments, they are already launch so the data are initialized just one time at the start.
I navigate between fragment when i switch of page on my app. 3 fragments on 1 activity create with MyPagerAdapter
here my code
The fragment
public class PageAdjuFragment extends VenteFragment {
Context context = getActivity();
public PageAdjuFragment() {
super();
// TODO Auto-generated constructor stub
}
public static PageAdjuFragment newInstance(String vente) {
PageAdjuFragment myFragment = new PageAdjuFragment();
Bundle args = new Bundle();
args.putString("vente", vente);
myFragment.setArguments(args);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
final View v = inflater.inflate(R.layout.page_adju_layout, container, false);
final Button b = (Button) v.findViewById(R.id.btconfp);
final RadioGroup radiopmt = (RadioGroup) v.findViewById(R.id.radiopmt);
final RadioButton rb1 = (RadioButton) v.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton) v.findViewById(R.id.rb2);
final AutoCompleteTextView tv1 = (AutoCompleteTextView) v.findViewById(R.id.actv1);
final AutoCompleteTextView tv2 = (AutoCompleteTextView) v.findViewById(R.id.actv2);
final EditText tv3 = (EditText) v.findViewById(R.id.edt);
// Recovery of the name of th folder/vente
Bundle arg = getArguments();
// final String vente = arg.getString("vente");
VenteFragment.nomvente = arg.getString("vente");
try {
InitObjet();
InitPart();
} catch (IOException e) {
e.printStackTrace();
}
for (String elem : getListpart()) {
Log.v("part", elem);
}
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, this.getListobject());
tv2.setAdapter(adapter2);
//some useless code ////////////////
}
The ActivityFragment
public class VenteActivity extends FragmentActivity {
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager2);
creationPage();
}
public void creationPage() {
// Creation of the list
List<Fragment> fragments = new Vector<Fragment>();
// Recovery
Intent sender = getIntent();
String extraData = sender.getExtras().getString("vente");
Log.v("Vente activity", extraData);
// Add Fragments in a list
Fragment frag1 = PageOffreFragment.newInstance(extraData); // frag1 //
// anymor
fragments.add(frag1);
Fragment frag2 = PageAdjuFragment.newInstance(extraData); // frag2 //
// anymor
fragments.add(frag2);
Fragment frag3 = PagePartFragment.newInstance(extraData); // frag3 //
// anymor
fragments.add(frag3);
// Creation of theadapter
this.mPagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
final ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager2);
// Affectation on the ViewPager
//pager.setOffscreenPageLimit(1);
pager.setAdapter(this.mPagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
}
});
}
// Overide for blocking the BACK Key of android device
#Override
public void onBackPressed() {
}
}
The class for work on the fragment :
public class VenteFragment extends Fragment {
protected static List<String> Listobject = null;
protected static List<String> Listpart = null;
protected static List<String> Listclient = null;
protected static String nomvente;
public List<String> getListobject() {
return Listobject;
}
public void setListobject(List<String> listobject) {
Listobject = listobject;
}
public List<String> getListpart() {
return Listpart;
}
public void setListpart(List<String> listpart) {
Listpart = listpart;
}
public List<String> getListclient() {
return Listclient;
}
public void setListclient(List<String> listclient) {
Listclient = listclient;
}
// Create the List of participant
public void InitClient() throws IOException {...}
// Create the List of participant
public void InitPart() throws IOException {
Log.v("VFvente", this.nomvente);
File DIR = new File(Environment.getExternalStorageDirectory() + "/Vente Acta/ListeVente/" + this.nomvente);
final String ADDRESS_FILE = DIR.toString() + "/" + "participant.csv"; // l'emplacement
// de
// achat.csv
Log.v("VFchemin", ADDRESS_FILE);
// if the file doesn't exit, create the file
File f = new File(ADDRESS_FILE);
if (!f.exists()) {
f.createNewFile();
Log.v("VFvente", "ici");
return;
}
List<String> data = new ArrayList<String>(); // liste contenant les
// element a adapter
// aux
// autotextview
// on applique le reader sur le fichier
CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
List<String[]> liste = reader.readAll();
int i = 0;
for (String[] ligne : liste) {
for (String col : ligne) {
Log.v("ligne " + i, "col " + col);
}
i++;
}
for (String[] elem : liste) { // pour chaque ligne
Log.v("VFdataelem0", elem[0]);
Log.v("VFdataelem1", elem[1]);
Log.v("VFdataelem2", elem[2]);
data.add(elem[1] + " " + elem[2]); // le nom et prenom
data.add(elem[0]); // le numero de participant pour la vente
}
reader.close();
Log.v("VFvente", "fin");
this.setListpart(data);
}
// Create the List of object
public void InitObjet() throws IOException {...}
}
The Page Adapter
public class MyPagerAdapter extends FragmentStatePagerAdapter {
List<Fragment> fragments;
FragmentManager mFragmentManager;
// On fournit à l'adapter la liste des fragments à afficher
public MyPagerAdapter(FragmentManager fm, List fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int pos) {
return this.fragments.get(pos);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
I have already try :
public int getItemPosition(Object object) {
return POSITION_NONE;
}
or adapter2.setNotifyOnChange(true);
or onResume
BUT maybe at the wrong place
and
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int i) {
Log.d("onPageSelected: ", i + "");
if(i == 0) {
PageOffreFragment frg = (PageOffreFragment)mPagerAdapter.instantiateItem(pager, i);
frg.onResume();
} else if (i == 1){
PageAdjuFragment frg = (PageAdjuFragment)mPagerAdapter.instantiateItem(pager, i);
frg.onResume();
}else if (i == 2) {
PagePartFragment frg = (PagePartFragment)mPagerAdapter.instantiateItem(pager, i);
frg.onResume();
}
}
in VenteActiivty
Nothing work :(
The creation is ok, the problem is the lifecycle of my fragment. (i think)
and where reload my fragment for update the list of data of my ACTV
Before you call notifychange make sure you add the new data first to you arraylist then call notify change
Finaly I have found a solution: this is my new FragmentActivity:
public class VenteActivity extends FragmentActivity {
private MyPagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager2);
creationPage();
}
public void creationPage() {
// Creation of the list
final List<Fragment> fragments = new Vector<Fragment>();
// Recovery
Intent sender = getIntent();
final String extraData = sender.getExtras().getString("vente");
Log.v("Vente activity", extraData);
// Add Fragments in a list
final Fragment frag1 = PageOffreFragment.newInstance(extraData); // frag1
fragments.add(frag1);
final Fragment frag2 = PageAdjuFragment.newInstance(extraData); // frag2
fragments.add(frag2);
final Fragment frag3 = PagePartFragment.newInstance(extraData); // frag3
fragments.add(frag3);
// Creation of theadapter
this.mPagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
final ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager2);
// Affectation on the ViewPager
// pager.setOffscreenPageLimit(1);
pager.setAdapter(this.mPagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int i) {
Log.d("onPageSelected: ", i + "");
mPagerAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
Related
PageAdapter:
class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
private int PAGE_COUNT = 3;
private String tabTitles[];
public SampleFragmentPagerAdapter(FragmentManager fm, String[] categorie) {
super(fm);
PAGE_COUNT = categorie.length;
tabTitles = new String[categorie.length];
for(int i = 0; i < categorie.length; i++){
tabTitles[i] = categorie[i];
}
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
return Pagina.newInstance(position + 1);
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
fragment activity :
public class Pagina extends Fragment {
private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
public static Pagina newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Pagina fragment = new Pagina();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
// Inflate the fragment layout we defined above for this fragment
// Set the associated text for the title
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pagina, container, false);
//TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
//tvTitle.setText("Fragment #" + mPage);
Log.e("STATO", "CI SIAMOOO");
return view;
}
public void getSecondScrollView(String str){
Log.e("ECCOLOO", "AVVIATO");
}
}
mainActivity :
public class PrincipaleActivity extends FragmentActivity{
public String[] categorie;
private String linguaApp = Locale.getDefault().getLanguage();
private Boolean linguaPresente = false;
private float scale;
private NetworkImageView imgProdotto;
private ViewPager pager;
private PagerSlidingTabStrip tabs;
private int screenWidth;
private int screenHeight;
private JSONObject dati;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principale);
Intent intent = getIntent();
try {
dati = new JSONObject(intent.getStringExtra("DatiArticolo"));
checkLingua();
} catch (JSONException e) {
e.printStackTrace();
Log.e("ERRORE", "Errore durante il parsing del JSONObject o del checkLingua");
}
((myMainScrollView)findViewById(R.id.scrollPrincipale)).setScrollingEnabled(false);
creaCategorie();
caricaImgProdotto();
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),categorie));
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
setDimensioniSchermo();
inizializzaPagina();
}
private void creaCategorie(){
categorie = new String[dati.optJSONArray("categorie").length()];
for (int h = 0; h < dati.optJSONArray("categorie").length(); h++){
try {
JSONObject temp = (JSONObject) dati.optJSONArray("categorie").get(h);
categorie[h] = temp.optJSONObject("nome").optString(linguaApp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void caricaImgProdotto(){
imgProdotto = (NetworkImageView) findViewById(R.id.imgProdotto);
String url = "http://46.101.209.16/"+dati.optJSONObject("anagrafica").optJSONObject(linguaApp).optJSONObject("img").optString("path");
Log.e("LINK IMG", url);
ImageLoader imageLoader = MyImageLoader.getInstance(this.getApplicationContext()).getImageLoader();
imageLoader.get(url, ImageLoader.getImageListener(imgProdotto, R.drawable.icona_flash, android.R.drawable .ic_dialog_alert));
imgProdotto.setImageUrl(url, imageLoader);
}
private void checkLingua() throws JSONException {
JSONArray valLingue = dati.optJSONObject("lingue").optJSONArray("lingueApp");
for(int i = 0; i < valLingue.length(); i++){
if(valLingue.get(i).equals(linguaApp)){
linguaPresente = true;
}
}
if (linguaPresente == false){
linguaApp = dati.optJSONObject("lingue").optString("principale");
}
Log.e("Lingua Scelta ",linguaApp);
}
private void setDimensioniSchermo(){
scale = getResources().getDisplayMetrics().density;
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
}
private void inizializzaPagina(){
imgProdotto.getLayoutParams().height = (screenWidth/3)*2;
tabs.getLayoutParams().height = (int)(scale * 30);
pager.getLayoutParams().height = screenHeight - (int)(scale * 30);
}
}
how can i call the method getSecondScrollView from my SampleFragmentPagerAdapter ?
i'm using this : https://github.com/jpardogo/PagerSlidingTabStrip
i need the methods inside the fragment for get outside some views
sorry for bad english, i'm italian :D
use this code in activity that have access to ViewPager :
Pagina fragment = (Pagina ) getSupportFragmentManager()
.findFragmentByTag( makeFragmentName(pager.getId(),page_index_of_pagina_fragment_inViewPager));
then call fragment.getSecondScrollView("str");
and this is makeFragmentName method that gets fragment name from adapter:
private String makeFragmentName(int viewPagerId, int index) {
return "android:switcher:" + viewPagerId + ":" + index;
}
note calls must be done after fragment completely loaded
Try using a callbacklistener, make Pagina implement an interface for example PagerAdapterListener which has the method onGetSecondScrollView(), like this:
public interface PagerAdapterListener {
void onGetSecondScrollView(String str);
}
Then add a PagerAdapterListener to your Adapter's constructor, so that your Adapter has a variable of the type PagerAdapterListener (new SampleFragmentPagerAdapter(..., ..., this)) . When you need to call the getSecondScrollView() method just call the onGetSecondScrollView() method on the interface (which is actually your Fragment).
And ofcourse dont forget to implement the PagerAdapterListener and its onGetSecondScrollView() method like this:
public class Pagina extends Fragment implements PagerAdapterListener {
#Override
public void onGetSecondScrollView(String str) {
getSecondScrollView(str);
}
}
I have an MainActivity with 4 fragments, the first fragment is consulting with spinners an webpage to get a json file. After refresh its information the second, third and fourth fragment will consult the internal DB (that has feedback with the json file) and show information. ...But. in the first fragment (have good function) after to check the second (dont have refresh) that have previous information to my fragment refresh, third same and when i check the fourth fragment then information in second and third are refreshed it. I dont know what is the problem.
public class MainActivity extends AppCompatActivity {
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);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
//fin de tablayout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.addTab(tabLayout.newTab().setText("Inicio y Seleccion"));
tabLayout.addTab(tabLayout.newTab().setText("Tiempo Semanal"));
tabLayout.addTab(tabLayout.newTab().setText("Suelos y lluvia"));
tabLayout.addTab(tabLayout.newTab().setText("Avisos y Alertas"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// manejo de tabs
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
final PagerAdapter adapter=new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
mViewPager.setAdapter(adapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
this is my pager adapter
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
tab_01 tab1 = new tab_01();
return tab1;
case 1:
tab_02 tab2 = new tab_02();
return tab2;
case 2:
tab_03 tab3 = new tab_03();
return tab3;
case 3:
tab_04 tab4 = new tab_04();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
this is my first fragment in this, you can choose an state with that you get localities when you press locality you get information
public class tab_01 extends Fragment {
String Salida;
public String html;
Spinner misMunicipios;
private Context miContexto;
private View manejadora;
public void workForm02()
{
}
private void RefreshInformation(Context context, String direccion)
{
final View vision= new View(context);
final String ruta=direccion.toString();
(new Thread()
{
.....
}
).start();
}
public void getInformationMT(View miVista)
{
final View vision=miVista;
(new Thread()
{
...
).start();
}
//manejo de llenado de los spinners -----------------------------------------------------
private AdapterView.OnItemSelectedListener myItemSelectedListener = new Spinner.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
int miEstado=0;
String consulta="";
if (parent.getId()==R.id.tab01_tablaselector_spinner_estado)
{
..... Fill localities when choose a state
}
if (parent.getId()==R.id.tab01_tablaselector_spinner_municipio)
{
if (!CadenaComaprativaMunicipio.contentEquals("0")) {
RefreshInformation(parent.getContext(), consulta.toString());
Log.v("MYLOG", "Spinners ==>:Refrscando informacion");
RefrescaInformacion miRecargaInfo = new RefrescaInformacion();
miRecargaInfo.RefrescaInformacion(miContexto, consulta.toString(), 1);
SystemClock.sleep(5000);
FillThisFragment(miContexto, manejadora);
workForm02();
} else
{
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
...
}
};
//fin de manejo de llenado del los spinners
private Void FillThisFragment(Context contexto,View miVista) {
---
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
// Inflate the layout for this fragment
View miVista=inflater.inflate(R.layout.tab_01, container, false);
manejadora=miVista;
miContexto=miVista.getContext();
TextView algo=(TextView) miVista.findViewById(R.id.tab01_vision_pronosticoTiempo);
if (algo.length() == 0) {
String miConsulta;
AlmacenDeDatos dataSource= new AlmacenDeDatos(this.getContext());
List<String[]> resultado = new ArrayList<String[]>();
miConsulta = "SELECT count(idestados) from estados";
resultado = dataSource.recuperaInfo2(miConsulta.toString());
String h[] = resultado.get(0);
int i= Integer.parseInt(h[0].toString());
if (i<30)
{
LectorArchivoInicializacion precarga=new LectorArchivoInicializacion();
precarga.lector(miVista.getContext());
SystemClock.sleep(500);
getInformationMT(manejadora);
algo.setText("Recuperando La Informacion, Por Favor Espere.");
SystemClock.sleep(5000);
}
AlmacenamientoDePreferencias verificacion =new AlmacenamientoDePreferencias( this.getContext());
String cadena=verificacion.leerUltimaUbicacion("mihtml");
Log.v("MYLOG","En el inicio la cadena de carga es ===>"+ cadena.toString());
if (cadena.isEmpty() || cadena.length()==0)
{
getInformationMT(miVista);
}
}
this.FillThisFragment(miVista.getContext(),miVista);
Spinner misEstados;
misEstados = (Spinner) miVista.findViewById(R.id.tab01_tablaselector_spinner_estado);
misEstados.setOnItemSelectedListener(myItemSelectedListener);
misMunicipios = (Spinner) miVista.findViewById(R.id.tab01_tablaselector_spinner_municipio);
misMunicipios.setOnItemSelectedListener(myItemSelectedListener);
LinkedList estadosMexicanos=new LinkedList();
estadosMexicanos.add( new Estados_Clase(0,"States"));
estadosMexicanos.add( new Estados_Clase(1,"Aguascalientes"));
estadosMexicanos.add( new Estados_Clase(2,"Baja California"));
estadosMexicanos.add( new Estados_Clase(3,"Baja California Sur"));
estadosMexicanos.add( new Estados_Clase(4,"Campeche"));
estadosMexicanos.add( new Estados_Clase(7,"Chiapas"));
estadosMexicanos.add( new Estados_Clase(8,"Chihuahua"));
estadosMexicanos.add( new Estados_Clase(5,"Coahuila"));
estadosMexicanos.add( new Estados_Clase(6,"Colima"));
estadosMexicanos.add( new Estados_Clase(9, "Distrito Federal"));
estadosMexicanos.add( new Estados_Clase(10,"Durango"));
estadosMexicanos.add( new Estados_Clase(11,"Guanajuato"));
estadosMexicanos.add( new Estados_Clase(12,"Guerrero"));
estadosMexicanos.add( new Estados_Clase(13,"Hidalgo"));
estadosMexicanos.add( new Estados_Clase(14,"Jalisco"));
estadosMexicanos.add( new Estados_Clase(15,"Estado de México"));
estadosMexicanos.add( new Estados_Clase(16,"Michoacán"));
estadosMexicanos.add( new Estados_Clase(17,"Morelos"));
estadosMexicanos.add( new Estados_Clase(18,"Nayarit"));
estadosMexicanos.add( new Estados_Clase(19, "Nuevo León"));
estadosMexicanos.add( new Estados_Clase(20, "Oaxaca"));
estadosMexicanos.add( new Estados_Clase(21,"Puebla"));
estadosMexicanos.add( new Estados_Clase(22,"Querétaro"));
estadosMexicanos.add( new Estados_Clase(23,"Quintana Roo"));
estadosMexicanos.add( new Estados_Clase(24,"San Luis Potosí"));
estadosMexicanos.add( new Estados_Clase(25,"Sinaloa"));
estadosMexicanos.add( new Estados_Clase(26,"Sonora"));
estadosMexicanos.add( new Estados_Clase(27,"Tabasco"));
estadosMexicanos.add( new Estados_Clase(28,"Tamaulipas"));
estadosMexicanos.add( new Estados_Clase(29,"Tlaxcala"));
estadosMexicanos.add( new Estados_Clase(30,"Veracruz"));
estadosMexicanos.add( new Estados_Clase(31,"Yucatán"));
estadosMexicanos.add( new Estados_Clase(32,"Zacatecas"));
ArrayAdapter spinner_adaptador=new ArrayAdapter(miVista.getContext(),android.R.layout.simple_spinner_item, estadosMexicanos);
spinner_adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
misEstados.setAdapter(spinner_adaptador);
AlmacenamientoDePreferencias algox=new AlmacenamientoDePreferencias(miVista.getContext());
String cadenaCarga=algox.leerUltimaUbicacion("mihtml");
Context miContext=this.getActivity();
return miVista;
}
}
this is my fragment 02
public class tab_02 extends Fragment {
public View miVista;
public static final String TAG ="tab_02";
private FragmentIterationListener mCallback=null;
public interface FragmentIterationListener{
public void onFragmentIteration();
}
public static tab_02 newInstance(){
tab_02 f=new tab_02();
f.RellenaForma();
return f;
}
public tab_02()
{
-vacum
}
public void RellenaForma()
{
Fill the form consulting data base inner phone
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
};
#Override
public void onResume ()
{
super.onResume();
this.RellenaForma();
}
#Override
public void onPause ()
{
super.onPause();
}
#Override
public void onStop ()
{
super.onPause();
}
#Override
public void onStart ()
{
super.onPause();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
miVista=inflater.inflate(R.layout.tab_02, container, false);
//----------------
Context miContext=this.getActivity();
------consult database and get information
------ fill fragment view
return miVista;
}
}
tab_03 and tab 04 are same of tab_02
I want to create soemthing like this:
The ViewPager is attached to an adapter which has 2 fragments. One to list the upcoming orders and the other to list the past orders.
So the image shown above has a main fragment which hosts the ViewPager, and the adapter creates 2 fragments as children of the main fragment.
For sake of simplicity I'll call the main fragment as "Parent fragment" and the two fragments supplied by the adapter as "children fragments".
Once the parent fragment is created or resumed it has to fetch a list of data from the server and pass it to the two children fragment(The children fragments will process the list of data and display the necessary data). Both the children fragments have a listView, and each listView row item is clickable.
Now, the data fetched by the parent fragment has to be passed to the children fragments before the ViewPager is attached to the adapter. So I do not attach the adapter to the ViewPager in the onCreate method of the parent fragment, but rather once the list of data is fetched, I attach the adapter to the ViewPager in the onPostExecute method of the async task after the data is fetched.
This works fine the first time, but once I click on a listView row item of the child fragment and then press the back button, the getItem() method of the adapter is not called, but the onResume methods of the children fragments are called even before the data is fetched from the server.
So I guess the android framework remembers that the children fragment have already been created, and does not recreate them again.
How do I ensure that the children fragments are created/called only after the data is fetched from the server in the parent fragment?
I am adding some code for clarity.
BookingHistory.java(Parent Fragment)
public class BookingHistory extends android.support.v4.app.Fragment {
ViewPager mPager;
SlidingTabLayout mTabs;
Toolbar toolBar;
View view;
private ProgressDialog progress;
private OrderTask mOrderTask = null;
UserFunctions userFunctions = null;
OrderFunctions orderFunctions = null;
private BookingHistoryListener mListener;
private List<Order> mOrderList;
PlacedOrders upcomingOrders;
PlacedOrders pastOrders;
public BookingHistory() {
// Required empty public constructor
}
#Override
public void onResume() {
super.onResume();
mOrderList = null;
mPager = null;
mTabs = null;
upcomingOrders = null;
pastOrders = null;
progress = new ProgressDialog(getActivity());
fetchOrders();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_booking_history, container, false);
toolBar = (Toolbar) view.findViewById(R.id.toolbar_s);
if (toolBar != null) {
TextView tv = (TextView) view.findViewById(R.id.toolbar_title);
toolBar.setTitle("");
tv.setText("History");
}
return view;
}
class MyPagerAdapter extends FragmentPagerAdapter {
String tabs[] = {"Upcoming", "Past"};
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
if (position == 0) {
upcomingOrders = PlacedOrders.newInstance(Constants.DATE_TODAY_FUTURE);
upcomingOrders.getOrderList(mOrderList);
return upcomingOrders;
} else {
pastOrders = PlacedOrders.newInstance(Constants.DATE_PAST);
pastOrders.getOrderList(mOrderList);
return pastOrders;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 2;
}
}
public void fetchOrders() {
if (mOrderTask != null) {
return;
}
progress.show();
mOrderTask = new OrderTask(getActivity());
mOrderTask.execute((Void) null);
}
public class OrderTask extends AsyncTask<Void, Void, Boolean> {
private final Activity mActivity;
OrderTask(Activity activity) {
mActivity = activity;
}
#Override
protected Boolean doInBackground(Void... params) {
userFunctions = new UserFunctions();
orderFunctions = new OrderFunctions();
return orderFunctions.getList(userFunctions.getToken(mActivity));
}
#Override
protected void onPostExecute(final Boolean success) {
mOrderTask = null;
progress.dismiss();
if (success) {
mOrderList = UserProfile.getOrders();
//attaching the view pager to adapter here!
mPager = (ViewPager) view.findViewById(R.id.pager);
mTabs = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mTabs.setDistributeEvenly(true);
mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.white);
}
});
mPager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
mTabs.setViewPager(mPager);
} else {
//Error handling stuff
}
}
}
}
PlacedOrders.java(Children Fragments)
public class PlacedOrders extends android.support.v4.app.Fragment {
private static String flag;
private int dateFlag;
private PlacedOrdersListener mListener;
UserFunctions userFunctions = null;
OrderFunctions orderFunctions = null;
private PlacedOrdersAdapter ordersAdapter;
private ProgressDialog progress;
private List<Order> mOrderList;
private List<Order> mPendingOrderList;
private List<Order> mCompletedOrderList;
public static PlacedOrders newInstance(int date) {
PlacedOrders fragment = new PlacedOrders();
Bundle args = new Bundle();
args.putInt(flag, date);
fragment.setArguments(args);
return fragment;
}
public void getOrderList(List<Order> orderList) {
this.mOrderList = orderList;
}
public PlacedOrders() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
dateFlag = getArguments().getInt(flag);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mPendingOrderList = new ArrayList<Order>();
mCompletedOrderList = new ArrayList<Order>();
return inflater.inflate(R.layout.fragment_placed_orders, container, false);
}
#Override
public void onResume() {
super.onResume();
displayOrders();
}
private void displayOrders() {
if (isVisible() && (mOrderList != null)) {
mPendingOrderList.clear();
mCompletedOrderList.clear();
ListView listViewOrder = (ListView) getView().findViewById(R.id.orderList);
if(dateFlag == Constants.DATE_TODAY_FUTURE) {
for(int i = 0; i < mOrderList.size(); i++) {
String status = mOrderList.get(i).status;
if(status.equals("PENDING") || status.equals("PROCESSING")) {
mPendingOrderList.add(mOrderList.get(i));
ordersAdapter = new PlacedOrdersAdapter(mPendingOrderList, getActivity().getLayoutInflater());
listViewOrder.setAdapter(ordersAdapter);
}
}
}
else if(dateFlag == Constants.DATE_PAST) {
for(int i = 0; i < mOrderList.size(); i++) {
String status = mOrderList.get(i).status;
if(status.equals("COMPLETE")) {
mCompletedOrderList.add(mOrderList.get(i));
ordersAdapter = new PlacedOrdersAdapter(mCompletedOrderList, getActivity().getLayoutInflater());
listViewOrder.setAdapter(ordersAdapter);
}
}
}
listViewOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//Display a new fragment on clicking
});
}
}
}
I had same issue and this was my solution :
In container fragment (fragment that contains tabs) in onViewCreated() method I created startFetch() method:
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
mViewPager = (ViewPager) v.findViewById(R.id.home_tab_pager);
mTabsHost= (TabLayout) getActivity().findViewById(R.id.appTabs);
startFetch();
}
Then in startFetch method i use Volley request and in onResponse method i update data and then add tabs :
public void startFetch(){
//Create volley request
String url = BuildConfig.API_GET_CATEGORIES;
final RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
updateCategoryData(response);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("ErrorFETCH", error.networkResponse.toString());
}
});
queue.add(request);
}
My udpateCategory() method :
public void updateCategoryData(final String stream) throws RemoteException, OperationApplicationException {
//Update the data to SQLITE
setupTabs();
}
My setupTabs() method :
public void setUpTabs(){
ArrayList<Category> categories = new ArrayList<>();
Cursor data = getActivity().getContentResolver().query(
Category.Entry.CONTENT_URI, // URI
Category.PROJECTION, // Projection
Category.Entry.COLUMN_NAME_PARENT_ID + " = ?", // Selection
new String[]{"0"}, // Selection args
null);
if (data != null) {
while(data.moveToNext()){
categories.add(new Category(data));
}
}
TabsPagerAdapter mAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager(), this.getActivity(), categories);
mViewPager.setAdapter(mAdapter);
mTabsHost.setupWithViewPager(mViewPager);
}
I have a viewpager with image fragments in it that works but on back was getting an error saying that there is no empty constructor. I made one but now my images don't show up because imageResourceId is null. I've tried a million things and can't figure it out.
public final class TestFragment extends Fragment {
String imageResourceId;
public TestFragment() {
}
public TestFragment(String cONTENT) {
imageResourceId = cONTENT;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
new DownloadImageTask((ImageView) image).execute(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
class TestFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
public String[] CONTENT;
private int mCount;
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar, R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms, R.drawable.perm_group_location };
public TestFragmentAdapter(FragmentManager fm, JSONArray photoData) {
super(fm);
// photoData = (JSONArray) userProfile.get("photos");
CONTENT = new String[photoData.length()];
mCount = photoData.length();
for (int i = 0; i < photoData.length(); i++) {
JSONObject mainPhoto;
try {
mainPhoto = photoData.getJSONObject(i);
CONTENT[i] = mainPhoto.getString("src_big");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
return new TestFragment(CONTENT[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
in the activity
mAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), photoData);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (LinePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
Android uses the empty constructor of a fragment to restore the fragment when there is a configuration change, that's why you can't modify it, and you can't override it because you get an error in eclipse. The best practice to pass arguments to a fragment, when instantiating it, is to use an static factory method:
public class TestFragment extends Fragment {
String imageResourceId;
public static TestFragment newInstance(String resource) {
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("Resource", resource);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResourceId = getArguments().getString("Resource");
}
}
To instanciate it you use the static method:
TestFragment fragment = TestFragment.newInstance("some string");
I have 4 Fragment Sector1,2,3,4 and I would like to transfer data between Fragment.
When I add product in sector 1 , the same product are insert inside the Edit in the Sector2.
If I switch between Sector 1 and 2 no problem, but when I go to the Sector3 and I return to sector1 for insert another product , the new product don't appear in the Edit on the Sector2.
Why? (this is the first Question), and I have implemented the same sharing data between Sector 1 and the Sector3 , but no product are added Why? (this is the second question)
Here the file:
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener,
OnShareMyDataListener{
private static final String TAG = "MainActivity";
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "MainActivity.onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Settare il tipo di navigazione
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// creo icona e scritta per il 1 Tab
Tab tab = actionBar.newTab()
.setText("Ordine")
.setTabListener(this)
.setIcon(R.drawable.ic_menu_agenda);
actionBar.addTab(tab);
// creo icona e scritta per il 2 Tab
tab = actionBar.newTab()
.setText("by Mail")
.setTabListener(this)
.setIcon(R.drawable.ic_menu_send);
actionBar.addTab(tab);
// creo icona e scritta per il 3 Tab
tab = actionBar.newTab()
.setText("by SMS")
.setTabListener(this)
.setIcon(R.drawable.phone);
actionBar.addTab(tab);
// creo icona e scritta per il 4 Tab
tab = actionBar.newTab()
.setText("Feedback")
.setTabListener(this)
.setIcon(R.drawable.ic_menu_revert);
actionBar.addTab(tab);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
// Il return new chiama le altre classi (i Fragment)
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new Sector1();
case 1:
return new Sector2();
case 2:
return new Sector3();
case 3:
return new Sector4();
default:
Fragment fragment = new Sector1();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
}
// Settare il titolo dei Sector
#Override
public int getCount() {
return 4;
}
}
#Override
public void onShareMyData(ArrayList<User> data) {
// TODO Auto-generated method stub
Sector2 Sector2Obj = (Sector2) getSupportFragmentManager().findFragmentById(R.id.pager);
Sector2Obj.setMessage(data);
Sector3 Sector3Obj = (Sector3) getSupportFragmentManager().findFragmentById(R.id.pager);
Sector3Obj.setMessage(data);
}
}
activity_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Sector1.java
public class Sector1 extends Fragment
{
private Button btnAggiungi;
private EditText EtQta,EtName;
ListView userList;
ArrayList<User> userArray = new ArrayList<User>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sector1, container, false);
btnAggiungi = (Button) rootView.findViewById(R.id.btn_aggiungi);
EtQta = (EditText) rootView.findViewById(R.id.Et_qta);
EtName = (EditText) rootView.findViewById(R.id.Et_name);
btnAggiungi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String Qta = "Qtà: "+ String.valueOf(EtQta.getText());
String Prodotto = "prodotto: "+ String.valueOf(EtName.getText());
userArray.add(new User(Prodotto, Qta));
sharedData.onShareMyData(userArray);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//return super.onCreateView(inflater, container, savedInstanceState);
return rootView;
}
OnShareMyDataListener sharedData;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
sharedData = (OnShareMyDataListener) activity/*getActivity()*/;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onShareMyData");
}
}
/**
* get datetime
* */
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy kk:MM", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
private String getItemUserArray() {
String str=null;
for (int i = 0; i < userArray.size(); i++) {
str += userArray.get(i).toString();
}
return str;
}
}
Sector2.java
public class Sector2 extends Fragment
{
private Button btnSendOrder,btnBrowseContact;
EditText nameField;
EditText emailField;
String subject = null;
TextView txt;
View rootView;
private Spinner mySpinnerEmail;
ArrayList<String> emailFornitore ;
ArrayList<String> aEmailList;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.sector2, container, false);
init(rootView);
return rootView;
}
void init(View rootView){
}
/******************************************************************************/
void setMessage(ArrayList<User> data){
String str;
txt = (TextView)rootView.findViewById(R.id.Et_ordine);
str = "[" + data.get(0).getName() + "]\n";
subject = str;
for (int i = 1; i < data.size(); i++) {
str += data.get(i).getName() + "(" + data.get(i).getQta() + ")\n";
}
txt.setText(str);
}
}
Sector3.java
public class Sector3 extends Fragment
{
Button buttonSend;
EditText textPhoneNo;
EditText textSMS;
TextView sms_count;
String subject = null;
TextView txt;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.sector3, container, false);
init(rootView);
return rootView;
}
void init(View rootView){
}
void setMessage(ArrayList<User> data){
String str;
txt = (TextView)rootView.findViewById(R.id.editTextSMS);
str = "[" + data.get(0).getName() + "]\n";// + data.get(0).getQta() + "]\n";
subject = str;
for (int i = 1; i < data.size(); i++) {
str += data.get(i).getName() + "(" + data.get(i).getQta() + ")\n";
}
txt.setText(str);
}
}
OnShareMyDataListener.java
public interface OnShareMyDataListener {
public void onShareMyData(ArrayList<User> data);
}
User.java
public class User {
String name;
String qta;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQta() {
return qta;
}
public void setQta(String qta) {
this.qta = qta;
}
public User(String name, String qta) {
super();
this.name = name;
this.qta = qta;
}
}
What does AppSectionPagerAdapter extends ?
If you look in the Android Doc you'll see that FragmentPagerAdapter Destroy the view Hierachy of your Fragment.
So when you go to section3, section1's view hierarchy is destroyed and when you go back, it is entirely reacreated but from scratch.
In your code the main problem is that the data you want to show are not stored. Keep in mind that in a Activity[Fragment[]] hierarchy the main point is the activity so you have to store your datas in the Activity to make it accessible from anywhere.
My advice:
In your Activity add a field ArrayList<User> data who will be updated :
#Override
public void onShareMyData(ArrayList<User> data) {
this.data = data;
}
And in your Sections's onCreate() :
sharedData = (OnShareMyDataListener) activity;
sharedData.data