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
Related
I created an Tab based application using viewpager and Tablayout. When i click a button new tabs are created with a child fragment.
What I need is to assign different tab id to my tabs and each should be different. I tried i take the position of tabs but unfortunately, it doesn't work. when i tried to toast the position using below code it works only initially when the first tab is created and doesn't work for other tabs created. I don't know why this happens. ALso if i delete the tabs the position is not getting correct.
So I need an alternative solution to assign a TAB id (number or name) to each new tabs created so that when each tab is created I need to call a request to server with that id and populate data based on the tab ID
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
My ViewPageradapter is:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
int selectedTabPosition;
private boolean doNotifyDataSetChangedOnce = false;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
removeTab(position);
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
//viewPager.setCurrentItem(getCount() - 1);
setupTabLayout();
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
ImageView tabItemAvatar =
(ImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
tabItemAvatar.setImageResource(R.drawable.boy);
return view;
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Parent Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS"+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void addPage(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
CHILD FRAGMENT :
public class FragmentChild extends Fragment {
String childname;
TextView textViewChildName;
EditText editText;
private GridView mGridView;
private ListItem mListItem;
private ListView mListview;
private ProgressBar mProgressBar;
private ProductViewAdapter mGridAdapter;
private ListViewAdapter mListAdapter = null;
private ArrayList<GridItem> mGridData;
private ArrayList<ListItem> mListData = null;
ListView listView;
CheckInterNetConnection check ;
Boolean isInternetPresent = false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
//textViewChildName = (TextView) view.findViewById(R.id.textViewChild);
//textViewChildName.setText(childname);
//editText = (EditText) view.findViewById(R.id.editText);
//editText.setText("");
}
private void setEvents() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("onActivityCreated","onActivityCreated");
mGridView = (GridView) getView().findViewById(R.id.gridView);
mGridData = new ArrayList<>();
mGridAdapter = new ProductViewAdapter(getActivity(), R.layout.grid_product_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
mListview = (ListView) getView().findViewById(R.id.list);
mListData = new ArrayList<>();
mListAdapter = new ListViewAdapter(getActivity(), R.layout.list_row, mListData);
mListview.setAdapter(mListAdapter);
}
#Override
public void onStart() {
super.onStart();
Log.e("onSTart","onSTart");
check = new CheckInterNetConnection(getActivity());
isInternetPresent = check.isConnectingToInternet();
if (isInternetPresent) {
//fetchProducts();
}
}
public void fetchProducts(){
Log.e("URL","http://13.126.17.194/products.php");
RestClientHelper.getInstance().get("http://13.126.17.194/products.php?tabid="{TAB ID HERE}, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
parseResult(response);
mListData.clear();
mListAdapter.setGridData(mListData);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
try {
ListItem items;
GridItem item = (GridItem) parent.getItemAtPosition(position);
items = new ListItem();
items.setName(item.getTitle());
items.setType(item.getDescription());
mListData.add(items);
}
catch(Exception e){
}
finally {
mListAdapter.setGridData(mListData);
}
}
});
}
#Override
public void onError(String error) {
}
});
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("products");
GridItem item;
if(posts.length() <= 0){
RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
ly.setVisibility(View.VISIBLE);
}
else {
// RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
//ly.setVisibility(View.INVISIBLE);
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String title = post.optString("name");
String description = post.optString("description");
String image = post.optString("image");
String qty = post.optString("qty");
String quantityin = post.optString("quantityin");
String price = post.optString("price");
item = new GridItem();
item.setId(id);
item.setTitle(title);
item.setDescription(description);
item.setImage(image);
item.setQuantity(qty);
item.setQuantityIn(quantityin);
item.setUnitprice(price);
mGridData.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
finally {
mGridAdapter.setGridData(mGridData);
}
}
}
PARENT FRAGMENT:
public class FragmentParent extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private ImageView add;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS"+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void addPage(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
//setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
PLEASE HELP ME TO SOLVE THIS
Here is my solution for the question:
First, create an id file under res/values named ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="tab_id_one" type="id"/>
<item name="tab_id_two" type="id"/>
</resources>
Then, within the code where tabs are created, do the following:
for (int i = 0; i< tabLayout.getTabCount(); i++) {
TabLayout.Tab mTab = tabLayout.getTabAt(i);
if (mTab != null) {
switch (i){
case 0:
View tabViewOne = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tabViewOne.setId(R.id.tab_id_one);
//ect..
break;
case 1:
View tabViewTwo = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tabViewTwo.setId(R.id.tab_id_two);
//ect..
break;
case 2:
//etc..
}
}
}
Note: Views tabViewOne and tabViewTwo can be made global variables where it will give access to their ids anywhere within the class/activity/fragment.
In your viewPager Adapter extends FragmentPagerAdapter this and include these methods and it will give new ID to every Fragment and when you add manually data in array and call notifyDataSetChange(), also call this method notifyChangeInPosition(mItems.size() - 1);.
From this the added item get a new ID.
private long baseId = 0;
ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return mItems.size();
}
//this is called when notifyDataSetChanged() is called
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
*
* #param n number of items which have been changed
*/
void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
You can use the setTag() method of TabLayout.Tab to use any Object you want as an identifier. You could do this in your setupTabLayout() method, where you are setting your custom view for each Tab.
For example, to use a String:
tabLayout.getTabAt(i).setTag("tab_" + i);
You can then later check the tag of each tab in your parent fragment with tab.getTag();
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.
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();
}
}
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);
}
}
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
}
});
}
}