Viewpager adapter in android - android

Why does my pager adapter doesn't want to start from my first item. When I start ContainerIspiti activity, and show first fragment, the view pager dones't show the right element. Insted of first, view pager shows the second element, and I can't to swipe to first element of my array list. Does anybody have solution.
Here is my code for ConainterIspiti
public class ContainerIspiti extends FragmentActivity{
private Button next, previous, odgovori, informacije;
private TextView textPitanja, brojPitanja;
private ViewPager pager;
private PagerAdapter mPagerAdapter;
public static ArrayList<Pitanja> getAllPitanja;
public static ArrayList<Pitanje_has_Slika> getAllImages;
private Intent intent;
private DBTools db = new DBTools(this);
private ProgressDialog pDialog;
private int broj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_container_pitanja);
Bundle bundle = new Bundle();
intent = getIntent();
Dohvati d = new Dohvati();
d.execute();
textPitanja = (TextView) findViewById(R.id.kategorijaTextViewPitanjeActivity);
brojPitanja = (TextView) findViewById(R.id.brojPitanjaTextViewPitanjeActivity);
pager = (ViewPager) findViewById(R.id.pagerPitanja);
pager.setCurrentItem(0, true);
bundle.putString("NAZIV_KATEGORIJE", intent.getStringExtra("NAZIV_KATEGORIJE"));
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.i("Position je sljedeci ", String.valueOf(position));
return PitanjaFragment.create(position);
}
#Override
public int getCount() {
Log.i("Velicina polja je ", String.valueOf(getAllPitanja.size()));
Log.i("Prvi eleemnt liste je", getAllPitanja.get(0).getTextPitanja());
return getAllPitanja.size();
}
}
private class Dohvati extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContainerIspiti.this);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
getAllPitanja = db
.getAllPitanja(intent.getStringExtra("id_kategorije"));
Log.i("Ovoliki je get all pitanja", String.valueOf(getAllPitanja.size()));
getAllImages = db.getAllPitanjaImages();
Log.i("ovoliko je slika", String.valueOf(getAllImages.size()));
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
brojPitanja.setText(String.valueOf(position) + "/" + String.valueOf(getAllPitanja.size()));
broj = position;
}
});
textPitanja.setText(intent.getStringExtra("NAZIV_KATEGORIJE"));
brojPitanja.setText(String.valueOf(broj) + "/" + getAllPitanja.size());
}
}
}
and here is my fragment activity
public class PitanjaFragment extends Fragment implements API{
public static final String ARG_PAGE = "page";
private int broj;
private ImageView image;
private TextView textPitanja;
private String uri;
private View view;
private ListView listView;
private Typeface custom_font;
private boolean odgovoreno, tocno;
private ArrayList<Odgovor> odgovorList;
private PitanjaAdapter adapter;
private DBTools db;
private List<Integer> kliknuti;
private HashMap<Integer, List<Integer>> odgBrojPitanja;
public static PitanjaFragment create(int pageNumber) {
PitanjaFragment fragment = new PitanjaFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public PitanjaFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
broj = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_pitanja, container, false);
image = (ImageView) view.findViewById(R.id.imageSlikaImageView);
image.setOnClickListener(this);
textPitanja = (TextView) view.findViewById(R.id.textPitanjaTextViewPitanjaActivity);
db = new DBTools(getActivity());
listView = (ListView) view.findViewById(R.id.listView);
updateDisplay((broj+1));
return view;
}
public void updateDisplay(int z) {
odgovoreno = false;
tocno = true;
textPitanja.setText(stripHtml(String.valueOf(ContainerIspiti.getAllPitanja.get(z).getTextPitanja())));
image.setImageBitmap(null);
//info = ContainerIspiti.getAllPitanja.get(z).getInfo();
Log.d("Postoji", ContainerIspiti.getAllImages.get(z).getNazivSlike() + ", ");
for (int j = 0; j < ContainerIspiti.getAllImages.size(); j++) {
if (ContainerIspiti.getAllImages.get(j).getIdPitanja() == ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
&& ContainerIspiti.getAllImages.get(j).getNazivSlike() != null) {
Log.i("Id pitanja slike + idpitanja pitanja + idSlike",
ContainerIspiti.getAllImages.get(j).getIdPitanja()
+ ", "
+ String.valueOf(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
+ ", "
+ ContainerIspiti.getAllImages.get(j).getIdSlika()));
image.setVisibility(View.VISIBLE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi);
//povecalo.setEnabled(true);
uri = PregledZnakova.PHOTOS_BASE_URL
+ ContainerIspiti.getAllImages.get(j).getNazivSlike();
int rounded_value = 40;
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.placeholder).showStubImage(R.drawable.placeholder).cacheInMemory().cacheOnDisc().displayer(new RoundedBitmapDisplayer(rounded_value)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
ImageLoader.getInstance().displayImage(uri, image,options);
break;
// }
} else {
image.setVisibility(View.GONE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi_neaktivno);
//povecalo.setEnabled(false);
}
}
odgovorList = db.getAllOdgovore(Integer.toString(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()));
adapter = new PitanjaAdapter(getActivity(),
R.layout.pitanja_entry, odgovorList);
listView.setAdapter(adapter);
for (int i=0;i<ContainerIspiti.getAllPitanja.size();i++){
if (ContainerIspiti.getAllPitanja.get(i).isTocno()){
Log.i("Ovo pitanje je tocno", ContainerIspiti.getAllPitanja.get(i).getTextPitanja());
}
}
}
#Override
public int getItemBroj() {
return broj;
}
#Override
public int getPosition() {
return broj;
}
#Override
public void setPosition(int position) {
this.broj = position;
}
#Override
public Fragment getFragment() {
return this;
}
}
Thanks for your time and your help.

In the onCreateView() method of your PitanjaFragment class, replace:
updateDisplay((broj+1));
with
updateDisplay(broj);
Try this. It should work.

Related

Update viewpager dynamically

I have a ViewPager. Data is stored in the database. I want update it dynamically. It is necessary that the element disappears immediately, but it does not work. Data is updated after i called method onCreate. I try all advice, but it does not help. What i did wrong? Help me find a solution, please.
TextPagerAdapter.java
public class TextPagerAdapter extends FragmentStatePagerAdapter {
List<String> data;
public TextPagerAdapter(FragmentManager fm, List<String> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new ItemFragment();
Bundle args = new Bundle();
args.putString(ItemFragment.ARG_TEXT, data.get(i));
args.putInt(ItemFragment.ARG_POSITION, i+1);
args.putInt(ItemFragment.ARG_COUNT, getCount());
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return data.size();
}
public String getTextVP(int i) {
return data.get(i);
}
#Override
public CharSequence getPageTitle(int position) {
return "Item " + (position + 1);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
ItemFragment.java
public class ItemFragment extends Fragment {
public static final String ARG_TEXT = "item_text";
public static final String ARG_POSITION = "item_position";
public static final String ARG_COUNT = "item_count";
TextView text1, textCount;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
Bundle args = getArguments();
text1 = (TextView) rootView.findViewById(R.id.text1);
text1.setText(args.getString(ARG_TEXT));
textCount = (TextView) rootView.findViewById(R.id.txtCount);
textCount.setText(args.getInt(ARG_POSITION) + " / " + args.getInt(ARG_COUNT));
return rootView;
}
}
StartAppScreen.java
public class StartAppScreen extends AppCompatActivity implements View.OnClickListener {
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
ViewPager mViewPager;
TextPagerAdapter mTextPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patters_layout);
List<String> data = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
init();
Intent intent = getIntent();
String condition = intent.getStringExtra("condition");
String column = intent.getStringExtra("column");
Boolean allWords = intent.getBooleanExtra("allWords", false);
data.addAll(getDataFromTable(mDb, column, condition, allWords));
if (allWords) Collections.shuffle(data);
mTextPagerAdapter = new TextPagerAdapter(
getSupportFragmentManager(), data);
mViewPager.setAdapter(mTextPagerAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnDel:
String s = mTextPagerAdapter.getTextVP(mViewPager.getCurrentItem());
/*Delete data from db*/
mDb.delete(TABLE_NAME, WORD_ROW_NAME + "= ?", new String[] {s} );
/*It is not work*/
mTextPagerAdapter.notifyDataSetChanged();
break;
}
}
private void init() {
try {
mDBHelper.updateDataBase();
} catch (IOException mIOException) {
throw new Error("UnableToUpdateDatabase");
}
try {
mDb = mDBHelper.getWritableDatabase();
} catch (SQLException mSQLException) {
throw mSQLException;
}
Button btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
Button btnDel = (Button) findViewById(R.id.btnDel);
btnDel.setOnClickListener(this);
mViewPager = (ViewPager) findViewById(R.id.pager);
}
}
Actually, you don't update list of string in your TextPagerAdapter. You update only in DB. Fetch data again and change the value of the data field in mTextPagerAdapter.

Tablayout on swipe not refreshing in android

I am implementing tablayout using view pager and in my scenario I have two tab. In my first tab I have add data which store in share preference. and when I move to second tab then data should be retrieve from share preference and show in listview. When I add the data from my first tab then data is added successfully but not show in my second tab means I have to close my application and again restart the app so that I can see saved the detail which saved from my first tab.
Below is my Activity code.
public class FragmentExample extends AppCompatActivity {
private ViewPagerAdapter viewPagerAdapter;
#BindView(R.id.tabCountryState)
TabLayout tabCountryState;
#BindView(R.id.viewPager)
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_example);
ButterKnife.bind(this);
setViewPager();
setTabIcon();
viewPager.setOffscreenPageLimit(2);
tabCountryState.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.e("Current tab is ", "===> " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager() {
// set Adaapter.
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentExample.this);
viewPager.setAdapter(viewPagerAdapter);
tabCountryState.setupWithViewPager(viewPager);
}
// set custom icon to tab in Tablayout.
private void setTabIcon() {
// First Tab
View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_first, null);
TextView tvFirsIcon = ButterKnife.findById(firstTab, R.id.tvFirsIcon);
tvFirsIcon.setText("First Tab");
tabCountryState.getTabAt(0).setCustomView(firstTab);
// First Tab
View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_second, null);
TextView tvSecondIcon = ButterKnife.findById(secondTab, R.id.tvSecondIcon);
tvSecondIcon.setText("Second Tab");
tabCountryState.getTabAt(1).setCustomView(secondTab);
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private FirstFragment firstFragment;
private SecondFragment secondFragment;
public ViewPagerAdapter(FragmentManager fm, Context mainActivity) {
super(fm);
context = mainActivity;
new FirstFragment();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
firstFragment = new FirstFragment();
return firstFragment;
case 1:
secondFragment = new SecondFragment();
return secondFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return " " + position;
}
}
}
Here is my FirstFragment in which I have added the data into share preference.
public class FirstFragment extends Fragment {
private View v;
#BindView(R.id.btnSubmit)
Button btnSubmit;
#BindView(R.id.edtCityName)
EditText edtCityName;
#BindView(R.id.spStateName)
Spinner spStateName;
private Unbinder unbinder;
private ArrayList<String> alStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private SpinnerStateAdapter spinnerAdapter;
private int spinnerPosition;
private String strCityName, strSpinnerValue;
#OnClick(R.id.btnSubmit)
public void submit(View view) {
if (spinnerPosition !=0) {
strCityName = edtCityName.getText().toString().trim();
alAllStateCity = SessinoManager.getCityList(getActivity());
if (strCityName.length() > 0) {
alAllStateCity.get(spinnerPosition).getAlCityName().add(new CityStateModel(strCityName));
} else {
}
// Save new data to Session.
SessinoManager.saveCityList(getActivity(), alAllStateCity);
SecondFragment.cityAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "Detail saved successfully ", Toast.LENGTH_SHORT).show();
edtCityName.setText("");
} else {
Toast.makeText(getActivity(), "Please select state", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_first, container, false);
unbinder = ButterKnife.bind(this, v);
// arraylist checking if data is available into session.
if(SessinoManager.getCityList(getActivity()).size()>0){
Log.e("First fragment "," if condition ");
alAllStateCity = SessinoManager.getCityList(getActivity());
alStateName = new ArrayList<>();
for(int i=0;i<alAllStateCity.size();i++){
alStateName.add(alAllStateCity.get(i).getStrStateName());
}
setStateSpinner();
}else{
loadArraylist();
setStateSpinner();
}
return v;
}
private void setStateSpinner() {
spStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
strSpinnerValue = alStateName.get(i).toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinnerAdapter = new SpinnerStateAdapter(getActivity(), alStateName);
spStateName.setAdapter(spinnerAdapter);
}
private void loadArraylist() {
alAllStateCity = new ArrayList<>();
alStateName = new ArrayList<>();
alStateName.add(0, "Select State");
alStateName.add("Gujarat");
alStateName.add("Maharashtra");
alStateName.add("Madhya Pradesh");
for (int i = 0; i < alStateName.size(); i++) {
alAllStateCity.add(new AllStateCityModel(alStateName.get(i), alAllStateCity.size(), new ArrayList<CityStateModel>()));
}
SessinoManager.saveCityList(getActivity(), alAllStateCity);
}
#Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
Log.e("First fragment "," on destroy");
}
}
Here is my SecondFragment in which I have to get saved detail from Share preference.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}
And I am saving data into Share preference which is given below.
public class SessinoManager {
private static final String CITY_PREFERENCE = "city_preference";
// Save data to share preference.
public static void saveCityList(Context context, ArrayList<AllStateCityModel> alAllPlayList) {
try {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonUsers = gson.toJson(alAllPlayList);
editor.putString("all_play_list", jsonUsers);
editor.commit();
// Check to save data into share preferent
for(int j=0;j<alAllPlayList.size();j++){
Log.e("State name ","----------------------"+alAllPlayList.get(j).getStrStateName());
ArrayList<CityStateModel> cityName = alAllPlayList.get(j).getAlCityName();
for(int i=0;i<cityName.size();i++){
Log.e("cityName "," in session ==> "+cityName.get(i).getStrCity());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static ArrayList<AllStateCityModel> getCityList(Context context)
{
SharedPreferences settings;
List<AllStateCityModel> users = new ArrayList<>();
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
if (settings.contains("all_play_list"))
{
String jsonUsers = settings.getString("all_play_list", null);
Gson gson = new Gson();
AllStateCityModel[] userItems = gson.fromJson(jsonUsers,AllStateCityModel[].class);
users = Arrays.asList(userItems);
users= new ArrayList<AllStateCityModel>(users);
}
return (ArrayList<AllStateCityModel>) users;
}
}
When I add new city detail into first tab then data is data successfully but when I swipe or move to next then data is not displaying and I have to restart whole application to get updated data from Share preference. Kindly help me to resolve this issue. Thanks in advance.
I have resolved the problem by implementing below method setUserVisibleHint.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
// Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.e("setUserVisibleHint","setUserVisibleHint "+isVisibleToUser);
if(isVisibleToUser==true){
loadArrayList(context);
}
}
#Override
public boolean getUserVisibleHint() {
Log.e("getUserVisibleHint","getUserVisibleHint "+super.getUserVisibleHint());
return super.getUserVisibleHint();
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}

Call method inside a fragment

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

Passing integer in ViewPager

I have 3 fragment in viewpager (LeftFragment, MidFragment and Right Fragment) LeftFragment contain a listview, when clicking on listview item,it sends an index (integer) from leftfragment to mid fragment, an image will be loaded on MidFragment. Errors here can be onCreateView happens before i set the arguments. So is there a way to solve my case. Sorry my skill english is bad. Thank you !
LeftFragment
public class LeftFragment extends Fragment{
private ListView listView;
private List<ParseObject> ob;
private ProgressDialog mProgressDialog;
private ListViewAdapter adapter;
private List<School> schoollist = null;
private View v;
MainActivity mainActivity = new MainActivity();
MidFragment midFragment = new MidFragment();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.left_fragment, container, false);
initComponent();
new RemoteDataTask().execute();
return v;
}
private void initComponent() {
listView = (ListView)v.findViewById(R.id.lv_left);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity.viewPager.setCurrentItem(1);
School school = schoollist.get(position);
midFragment.reloadData(Integer.parseInt(school.getIndex()));
}
});
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Please wait a moment...");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
schoollist = new ArrayList<School>();
try{
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("School");
query.orderByAscending("index");
ob = query.find();
for (ParseObject name : ob){
School map = new School();
map.setIndex(String.valueOf(name.get("index")));
map.setCount(String.valueOf(name.get("count")));
map.setName(String.valueOf(name.get("name")));
schoollist.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new ListViewAdapter(getActivity(), schoollist);
listView.setAdapter(adapter);
mProgressDialog.dismiss();
super.onPreExecute();
}
}
}
MidFragment
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private DisplayImageOptions options;
private ImageLoader imageLoader = ImageLoader.getInstance();
private Context mContext;
private ImageLoadingListener animateFirstListener;
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
// mImageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent(view);
mContext = container.getContext();
return view;
}
private void initComponent(View view) {
mImageView = (ImageView) view.findViewById(R.id.image);
mVideoView = (VideoView) view.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
objectList.clear();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
if (parseObject.getNumber("type") == (Number)1){
}else{
// mVideoView.setVisibility(View.GONE);
// mImageView.setVisibility(View.VISIBLE);
imageLoader.displayImage(parseFile.getUrl(), mImageView, options, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
MainActivity
public class MainActivity extends FragmentActivity{
public static MyPagerFragment myPagerFragment;
public static ViewPager viewPager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.viewPager);
myPagerFragment = new MyPagerFragment(getSupportFragmentManager());
viewPager.setAdapter(myPagerFragment);
viewPager.setCurrentItem(1);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public static class MyPagerFragment extends FragmentStatePagerAdapter {
public MyPagerFragment(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new LeftFragment();
case 1: return new MidFragment();
case 2: return new RightFragment();
default: return null;
}
}
#Override
public int getCount() {
return 3;
}
}
}
LeftFragment
public class LeftFragment extends Fragment{
OnImageSelectedListener mCallback;
public interface OnImageSelectedListener {
public void onImageSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnImageSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnImageSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onImageSelected(position);
}
}
Main Activity
public class MainActivity extends FragmentActivity implements HeadlinesFragment.OnImageSelectedListener{
public void onArticleSelected(int position) {
midFragment.setImage(position);
}
}
MidFragment
public class MidFragment extends Fragment {
setImage(int position){
//set Image here this method will be called the user select a list in left fragment
}
}

Intent in AsyncTask for FragmentPagerAdapter

I have implemented a FragmentPagerAdapter of 4-lashes, and in each of them I load a fragment with a different view.
In one of them, pressing an image executed a AsyncTask to obtain a series of data from a server and loads a new class through an intent on the postExecute() method as follows:
//AsyncTask
private static class LoadJSON extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
mProgressItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mProgressItem.setVisible(true);
mProgressItem.setActionView(R.layout.actionbar_indeterminate_progress);
mProgressItem.expandActionView();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
String data = MetodosJSON.getHttpResponse(url);
MetodosJSON.parseaJSON2(data, ini.ac);
return params[1];
}
protected void onPostExecute(String titulo) {
// start new activity
Intent i = new Intent(ini.c, PantallaInfo.class);
i.putExtra("title", titulo);
i.putExtra("URLser", urlSer);
ini.startActivity(i);
mProgressItem.setVisible(false);
}
}
I had this functionality in one activity and worked perfectly. Now to make the call from the fragment I have to make calls using a variable static of this class ('ini') and I get error in the line of code 'ini.startActivity (i),':
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3351)
at android.support.v4.app.FragmentActivity.startActivityForresult(FragmentActivity.java:674)
at android.app.Activity.startActivity(Activity.java:3522)
at com.packet.ClassName.AsyncTask.onPostExecute(ClassName.java:432)
I hope someone can help me, please.
Thank you very much.
...continue...my whole class
package com.test;
import ...
public class IniSelCategoria extends SherlockFragmentActivity {
static String urlIni;
static String urlSer;
GridView mGrid;
static Dialog dial;
DisplayMetrics metrics = new DisplayMetrics();
static int width, height;
private static MenuItem mProgressItem;
MyAdapter mAdapter;
ViewPager mViewPager;
static Context c, ac;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.iniselcategoria);
c = getBaseContext();
ac = getApplicationContext();
// Configuration
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mAdapter = new MyAdapter(getSupportFragmentManager());
for(int i=0; i<4; i++) {
Fragment fragment = null;
switch(i) {
case 0:
fragment = Fragment1.newInstance();
break;
case 1:
fragment = Fragment2.newInstance();
break;
case 2:
fragment = Fragment3.newInstance();
break;
case 3:
fragment = Fragment4.newInstance();
break;
}
mAdapter.addFragment(fragment);
}
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
// Intent information
Bundle recibido = getIntent().getExtras();
if(recibido != null) {
urlIni = recibido.getString("URLini");
}
}
final static IniSelCategoria ini = new IniSelCategoria();
//Options Menu
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.iniselcategoria, menu);
mProgressItem = menu.findItem(R.id.MenuProgress);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.MenuBuscador) {
Intent ic3 = new Intent(getBaseContext(), Menu_Buscador.class);
startActivity(ic3);
return true;
}else {
return super.onOptionsItemSelected(item);
}
}
//Creation of images
public static class ImageAdapter extends BaseAdapter {
private Context mContext;
final AppJSON json = (AppJSON) (IniSelCategoria.ac);
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return json.json1.GetNumSer();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView img;
if (convertView == null) {
img = new ImageView(mContext);
img.setAdjustViewBounds(true);
img.setScaleType(ImageView.ScaleType.FIT_CENTER);
} else {
img = (ImageView) convertView;
}
final String titulo = json.json1.GetTitle(position);
final int idSer = json.json1.GetIdSer(position);
// Configuration images
if("Recursos Naturales".equals(titulo)) {
img.setImageResource(R.drawable.ic_recursosnaturales);
}else if("Competitividad".equals(titulo)) {
img.setImageResource(R.drawable.ic_competitividad);
}else if("Calidad de Vida".equals(titulo)) {
img.setImageResource(R.drawable.ic_calidaddevida);
}else if("Participación".equals(titulo)) {
img.setImageResource(R.drawable.ic_participacion);
}else if("Transporte".equals(titulo)) {
img.setImageResource(R.drawable.ic_transporte);
}else{
Toast.makeText(IniSelCategoria.c, "Error", Toast.LENGTH_SHORT).show();
}
img.setOnClickListener(new ImageView.OnClickListener() {
public void onClick(View v) {
urlSer = urlIni + idSer;
// get data from the server
new CargarJSON(mContext).execute(urlSer, titulo);
}
});
return img;
}
}
//AsyncTask
private static class CargarJSON extends AsyncTask<String, Void, String> {
Context mContext;
public CargarJSON(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mProgressItem.setVisible(true);
mProgressItem.setActionView(R.layout.actionbar_indeterminate_progress);
mProgressItem.expandActionView();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
String data = MetodosJSON.getHttpResponse(url);
MetodosJSON.parseaJSON2(data, IniSelCategoria.ac);
return params[1];
}
#Override
protected void onPostExecute(String titulo) {
super.onPostExecute(titulo);
// start new activity
Intent i = new Intent(mContext, PantallaInfo.class);
i.putExtra("title", titulo);
i.putExtra("URLser", urlSer);
ini.startActivity(i);
mProgressItem.setVisible(false);
}
}
public static class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList;
public MyAdapter(FragmentManager fm) {
super(fm);
mFragmentList = new ArrayList<Fragment>();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return ((CustomFragment) mFragmentList.get(position)).getPageTitle();
}
}
public static abstract class CustomFragment extends Fragment {
public abstract String getPageTitle();
}
public static class Fragment1 extends CustomFragment {
public static Fragment newInstance() {
Fragment f = new Fragment1();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.iniselareas, container, false);
// Some codes for layout such as findViewById
final GridView gridServ = (GridView)view.findViewById(R.id.myGrid);
if(height > width) {
gridServ.setNumColumns(1);
}else {
gridServ.setNumColumns(2);
}
gridServ.setAdapter(new ImageAdapter(getActivity()));
return view;
}
#Override
public String getPageTitle() {
// return TITLE_FOR_FRAGMENT
return "ÁREAS TEMÁTICAS";
}
}
public static class Fragment2 extends CustomFragment {
...
}
public static class Fragment3 extends CustomFragment {
...
}
public static class Fragment4 extends CustomFragment {
...
}
}
I don't know what c is
gridServ.setAdapter(new ImageAdapter(c)); // is c activity context
or
gridServ.setAdapter(new ImageAdapter(getActivity()));
getActivity()
public final Activity getActivity ()
Added in API level 11
Return the Activity this fragment is currently associated with.
Then you have
public ImageAdapter(Context c) {
mContext = c;
// you get the activity context here
// you can use the same
}
Pass the activity context to the constructor of asynctask.
new LoadJSON(mContext).execute(url,title);
// using mContext initialized in ImageAdapter
Then in the asynctask constructor
Context mContext;
public LoadJSON(Context context)
{
mContext = context; // get activity context
}
Also
#Override
protected void onPreExecute() {
super.onPreExecute();
Then
#Override
protected void onPostExecute(String titulo) {
super.onPostExecute(titulo);
Also use mContext to startActivity
Intent i = new Intent(mContext, PantallaInfo.class);
mContext.startActivity(i);
startActivity is a method of Activity class. Requires Activity context.

Categories

Resources