2

I'm somehow new to Android, specially Fragments and i'm facing this problem I cannot solve, I have searched for it here and found some similar problems but none of them helped solve mine:

I have one activity containing a TabLayout and a ViewPager and an adapter to fragments. the PageAdapter gets some data from the database and sends it to the three fragments. The user can change the date in the activity and it should reload new data.

Once the activity loads its first time everything works fine on APIs 16/17 but from 18 beyond it doesn't show any data. Also, when the user changes the date, the first and last tabs update data correctly, but the second and middle tab keeps showing the past content.

Code for CardapioActivity

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
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.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;


import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;

public class CardapioActivity extends AppCompatActivity {

public TextView msg, data;
private DatePickerDialog toDatePickerDialog;
private SimpleDateFormat dateFormatter;
private Calendar myCalendar;
private TabLayout tabLayout;
private ViewPager viewPager;
private String restaurante;
private ArrayList<String> lista = new ArrayList<>();

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

    msg = (TextView) findViewById(R.id.tv1);
    data = (TextView) findViewById(R.id.data);

    Intent intent = getIntent();
    restaurante = intent.getStringExtra("restaurante");
    lista = intent.getStringArrayListExtra("lista");

    msg.setText(restaurante);
    msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            alertaRestaurante();
            carregaFragment();
        }
    });


    //formata data e possibilita seleção a partir do calendário
    myCalendar = Calendar.getInstance();
    dateFormatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
    data.setText(dateFormatter.format(myCalendar.getTime()).toString());
    data.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            alertaCalendario();
            carregaFragment();
        }
    });


    //fecha página caso clicado em close
    final ImageButton close = (ImageButton) findViewById(R.id.close);
    close.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //volta pra activity do mapa
            Intent intent = new Intent(CardapioActivity.this, MainActivity.class);
            CardapioActivity.this.startActivity(intent);
            CardapioActivity.this.finish();
        }
    });

    carregaFragment();
}

The method carregaFrament() is responsible for creating the TabLayot and setting it up with the ViewPager

private void carregaFragment(){
    //viewPager
    viewPager = (ViewPager) findViewById(R.id.vp);
    viewPager.setAdapter(new CustomSlidePageAdapter(getSupportFragmentManager(), CardapioActivity.this));

    //tabLayout
    tabLayout = (TabLayout) findViewById(R.id.tab);
    tabLayout.setupWithViewPager(viewPager);
}

This is the PagerAdapter

private class CustomSlidePageAdapter extends FragmentStatePagerAdapter {

    Bundle bundle = new Bundle();
    private String pages [] = {"DESJEJUM", "ALMOÇO", "JANTA"};
    private Context context;

    public CustomSlidePageAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                ArrayList<Cardapio> lista_desjejum = carregaCardapio("desjejum", msg.getText().toString(), data.getText().toString());
                bundle.putParcelableArrayList("lista_desjejum", lista_desjejum);

                // set Fragmentclass Arguments
                DesjejumFragment desjejum = new DesjejumFragment();
                desjejum.setArguments(bundle);

                return desjejum;
            case 1:
                ArrayList<Cardapio> lista_almoco = carregaCardapio("almoco", msg.getText().toString(), data.getText().toString());
                bundle.putParcelableArrayList("lista_almoco", lista_almoco);

                // set Fragmentclass Arguments
                AlmocoFragment almoco = new AlmocoFragment();
                almoco.setArguments(bundle);

                return almoco;
            case 2:
                ArrayList<Cardapio> lista_janta = carregaCardapio("janta", msg.getText().toString(), data.getText().toString());
                bundle.putParcelableArrayList("lista_janta", lista_janta);

                // set Fragmentclass Arguments
                JantaFragment janta = new JantaFragment();
                janta.setArguments(bundle);

                return janta;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return pages.length;
    }

    @Override
    public CharSequence getPageTitle(int position){
        return pages[position];
    }

}

And here is one example of the three Fragments, they are all similarly coded

import android.support.v4.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import java.util.ArrayList;


public class DesjejumFragment extends ListFragment {
private ArrayList<Cardapio> c = new ArrayList<>();

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

    c = getArguments().getParcelableArrayList("lista_desjejum");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_desjejum, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ListaCardAdapter adapter = new ListaCardAdapter(getActivity(), c);
    setListAdapter(adapter);
}

}

Here are some pictures to exemplify the problem:

first time on the left, changed date on the right

in the middle tag it doesn't change

Here are some logcat when I try switching tabs on API level >18

04-12 23:13:16.831 31009-31009/br.ufrrj.lothar.rural D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
04-12 23:13:16.941 31009-7797/br.ufrrj.lothar.rural I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
04-12 23:13:16.941 31009-7797/br.ufrrj.lothar.rural I/qtaguid: Tagging socket 48 with tag ad7277400000000{181872500,0} for uid -1, pid: 31009, getuid(): 10169
04-12 23:13:16.981 31009-7797/br.ufrrj.lothar.rural I/qtaguid: Untagging socket 48
04-12 23:13:17.551 31009-31009/br.ufrrj.lothar.rural D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
04-12 23:13:19.661 31009-31009/br.ufrrj.lothar.rural D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
04-12 23:13:19.791 31009-7859/br.ufrrj.lothar.rural I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
04-12 23:13:19.791 31009-7859/br.ufrrj.lothar.rural I/qtaguid: Tagging socket 48 with tag ad7277400000000{181872500,0} for uid -1, pid: 31009, getuid(): 10169
04-12 23:13:19.841 31009-7859/br.ufrrj.lothar.rural I/qtaguid: Untagging socket 48
04-12 23:13:20.741 31009-31009/br.ufrrj.lothar.rural D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
04-12 23:13:22.611 31009-31009/br.ufrrj.lothar.rural D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
04-12 23:13:22.741 31009-7910/br.ufrrj.lothar.rural I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
04-12 23:13:22.741 31009-7910/br.ufrrj.lothar.rural I/qtaguid: Tagging socket 48 with tag ad7277400000000{181872500,0} for uid -1, pid: 31009, getuid(): 10169
04-12 23:13:22.781 31009-7910/br.ufrrj.lothar.rural I/qtaguid: Untagging socket 48

Can anybody help me? P.S.: sorry in advance for some variables and methods in Portuguese, it may be confusing.

UPDATE: on API level 21 it shows content only in the middle tab, 23 it show nothing.

Lothar
  • 21
  • 3
  • I would recommend not doing this with arguments, as those can only be sent when the Fragment is initialized. As you are seeing, with a ViewPager it's not predictable when the Fragments are created, so you shouldn't rely on that. In addition, you should only be concerned about updating the data on the page that is currently viewed. Take a look at this answer, which shows how to dynamically update data for the current Fragment shown in the ViewPager: http://stackoverflow.com/a/36504458/4409409 – Daniel Nugent Apr 13 '17 at 03:15
  • I wish I could vote for your answer man (i cannot vote on comments can i?) i followed your advice and started loading the data before creating the Fragments and now it works in all versions of android. I'm still getting an error though, whenever i update it the middle fragment won't show content, any idea of what could it be? @DanielNugent P.s.: the onpagechange thing didn't work :/ – Lothar Apr 22 '17 at 18:47

1 Answers1

0

For the first question please upload some logs from Logcat and the imports to help the community to understand why you have this problem.

For the second problem you need to change the limit for the fragments. This is very important. Use viewPager.setOffscreenPageLimit(int);

Roger RV
  • 132
  • 3
  • 15
  • thanks for answering @Roger RV!! I have updated with the imports and logcat, also I have tried using setOffscreenPageLimit(int) before setting the integer to 2 since I only have three tabs and it stops loading the content. It doesn't allow me to use break in the switch because of the return – Lothar Apr 13 '17 at 02:19