In tabbed activity, retrive data from Firebase doesn't work well - java

In the following code I tried to read data from Firebase, and use this to create dynamically cardviews, but when the program starts, the ArrayList is empty while I click on the third tab, and back to the first. After a few days of finding out the problem, I couldn't solve this by myself.
MainScreen.java:
public class MainScreen extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private static final String TAG = "MainScreen";
public List<BusNumber> jaratok= new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.getTabAt(0).setText("Járatok");
tabLayout.getTabAt(1).setText("Megállók");
tabLayout.getTabAt(2).setText("Tervező");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("bus_number");
myRef.addValueEventListener((new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
jaratok = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
jaratok.add(new BusNumber(ds.child("CodeNumber").getValue(String.class),ds.child("BusRouteName").getValue(String.class)));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w("TAG","Failed to read data.",databaseError.toException());
}
}));
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Fejlesztés alatt", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
JaratokTab1 tab1 = new JaratokTab1();
return tab1;
case 1:
MegallokTab2 tab2 = new MegallokTab2();
return tab2;
case 2:
TervezoTab3 tab3 = new TervezoTab3();
return tab3;
default:
return null;
}
}
}
JaratokTab1.java:
public class JaratokTab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.jaratok_tab1, container, false);
MainScreen m2 = (MainScreen) getActivity();
for (BusNumber n : m2.jaratok) {
Log.d("Ertek: ", n.getName());
}
CardView cardView = new CardView(getContext());
TextView tv = new TextView(getContext());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
cardView.setLayoutParams(params);
cardView.setVisibility(View.VISIBLE);
cardView.setCardElevation(9);
cardView.setPadding(15, 15, 15, 15);
cardView.setRadius(9);
tv.setTextColor(Color.RED);
tv.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
cardView.addView(tv);
LinearLayout linearLayout = rootView.findViewById(R.id.linearID);
linearLayout.setPadding(60,15,50,30);
linearLayout.addView(cardView);
return rootView;
}
//also tried this:
/* #Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MainScreen m2 = (MainScreen) getActivity();
for (BusNumber n : m2.jaratok) {
Log.d("Ertek: ", n.getName());
}
}*/
}

By the time you are looping through m2.jaratok, the data isn't still available and that's why your list is empty. Firebase APIs are asynchronous, meaning that onDataChange() method returns immediately after it's invoked, and the callback from the Task it returns, will be called some time later.
There is no guarantee about how long it will take, it may take from a few hundred milliseconds to a few seconds before that data is available and can be used. Because that method returns immediately, your jaratok list you're trying to use it outside the callback is empty.
Basically, you're trying use a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.
A quick solve for this problem would be to use jaratok list only inside the onDataChange() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Related

How do I use back stack or get getChildFragmentManager() with this specific pager adapter in order to use the back button?

I'm using Fragments to change scenes in my application, and I've come across the problem where when the phone back button is pressed, the application closes. How would I make it so when the back button is pressed, the previous fragment opens.
I searched for solutions and there are quite a few like using getChildFragmentManager or back stack. I just don't know how to implement it for my specific state pager adapter, of which I followed a youtube video tutorial for.
SectionsStatePagerAdapter.java:
public class SectionsStatePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
public SectionsStatePagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public SectionsStatePagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
public void addFragment(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
public SectionsStatePagerAdapter mSectionsStatePagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Fragment Stuff:
mSectionsStatePagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
//SetUpPager:
setupViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager){
SectionsStatePagerAdapter adapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new MainPageFragment(),"MainPage"); //0
adapter.addFragment(new CoffeePageFragment(),"CoffeePage"); //1
adapter.addFragment(new RegularCoffeeFragment(),"RegularCoffeePage"); //2
viewPager.setAdapter(adapter);
}
public void setViewPager(int fragmentNumber){
mViewPager.setCurrentItem(fragmentNumber);
}
}
CoffeePageFragment.java:
public class CoffeePageFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_coffee_page,container,false);
btnRegularCoffee = view.findViewById(R.id.regular_coffee_button);
btnRegularCoffee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setViewPager(2);
}
});
return (view);
}
}
In conclusion, how do I make it so when the device back button is pressed, it will go back to the previous fragment?
In previous versions of the AppCompatActivity implementation it was enough to override onBackPressed() in your activity, newer versions dictate to implement the OnBackPressedCallback, like shown here: https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher.html
public class FormEntryFragment extends Fragment {
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(
true // default to enabled
) {
#Override
public void handleOnBackPressed() {
showAreYouSureDialog();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(
this, // LifecycleOwner
callback);
}
}
It might still be ok to use onBackPressed on the Activity level, though.

Listen DialogFragment dismiss event from ViewPager Fragment

There are lot of (duplicate) questions and answers are available, I went through almost all of them and failed. On reference of this question, I made some changes recently.
Brief : In my app, MainActivity holds Fragment View Pager and FrangmentA,B and C. FrangmentA Shows a DialogFragment CDialog onClik. After dismissing CDialog I need to Call FragmentA's doReload() which is not happening here.
MainActivity
protected void onCreate(Bundle savedInstanceState){
...
mSectionsPageAdapter = new FragmentAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
int defaultValue = 0;
int page = getIntent().getIntExtra("One", defaultValue);
mViewPager.setCurrentItem(page);
}
private void setupViewPager(ViewPager viewPager)
{
FragmentAdapter adapter = new
FragmentAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentA(), "FragA");
adapter.addFragment(new FragmentB(), "FragB");
adapter.addFragment(new FragmentC(), "FragC");
viewPager.setAdapter(adapter);
}
FragmentA
public class FragmentA extends Fragment implements CDialog.Dismissed{
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
...
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
FragmentManager fm = getActivity().getFragmentManager();
DialogFragment f = new CDialog();
f.show(fm, "CDialog");
}
});
#Override
public void dialogDismissed() {
Log.e(DFD_1, "dialogDismiss Called" );// <-- This is not working*
doReload();
}
}
And CDialogue
public class CDialog extends DialogFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
...
dfd_1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
getDialog().dismiss(); //<--when this happens*
}
});
}
#Override
public void onDismiss(DialogInterface dialog) {
if (getActivity() != null && getActivity() instanceof Dismissed) {
((Dismissed) getActivity()).dialogDismissed();
}
super.onDismiss(dialog);
}
public interface Dismissed {
public void dialogDismissed(); //<-- FragmentA implements this
}
}
You can always have direct callback to your Fragment itself.
First step, is to set targetFragment using setTargetFragment():
DialogFragment#setTargetFragment(Fragment fragment, int requestCode);
I do it this way:
public void showDialogFragment(Fragment targetFragment, AppCompatDialogFragment appCompatDialogFragment, int requestCode) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
appCompatDialogFragment.setTargetFragment(targetFragment, requestCode);
fragmentTransaction.add(appCompatDialogFragment, appCompatDialogFragment.getClass().getSimpleName());
fragmentTransaction.commitAllowingStateLoss();
}
and then call to this method to open dialog fragment as:
public static final int RC_CDIALOG = 111;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showDialogFragment(FragmentA.this, new CDialog(), RC_CDIALOG);
}
});
Then, in your DialogFragment's onDismissListener(), have some code like below:
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (getTargetFragment() instanceof FragmentA)
((FragmentA) getTargetFragment()).doReload();
}
What you did this way is:
Show Dialog Fragment "CDialog" along with telling it that your target fragment is "FragmentA" whose reference you can use incase you have something to do with it. In your case you had to call doReload();

getArguments() returns null when pass String Array from container Activity to fragment

I have an activity which has a fragment in which I have to pass String array from activity , when I do this through following code null pointer exception occurs Please help
Main2Activity.java
public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback, AsyncResponse{
String[] check = {
"KFC bundle",
"Pizza Hut b",
"Pizza Point b"
} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
newString = intent.getLongExtra("user_id", newString);
Bundle bundle = new Bundle();
bundle.putStringArray("name", check);
Log.i("okkkkk", "Name Put: " + check[1]);
Deals deals = new Deals();
deals.setArguments(bundle);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
try {
switch (position) {
case 0: {
MapsFragment mapsActivity=new MapsFragment();
return mapsActivity;
}
case 1: {
Deals deals = new Deals();
return deals;
}
}
}
catch ( Exception e)
{
Log.i("okkk", "Exception 1 : " + e);
}
Deals.java `
public class Deals extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main2,null);
// bundle = this.getArguments();
String[] name = getArguments().getStringArray("name");
Log.i("okkkkk", "Name String: " + name);
// String[] deal = getArguments().getStringArray("deal");
ListView listview =(ListView)view.findViewById(R.id.DealsListView);
customList adapter = new customList(getActivity(), web, imageId,deal);
listview.setAdapter(adapter);
return view;
}`
java.lang.NullPointerException
at app.com.example.saeed.fypephaseone.Deals.onCreateView(Deals.java:42)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1632)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:637)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1235)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1083)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1609)
at android.view.View.measure(View.java:16842)
You need to use the instance deals inside your PagerAdapter's getItem function instead of creating a new Fragment instance which has no bundle as argument
1.) Make your deals instance global to class
public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback, AsyncResponse{
String[] check = {
"KFC bundle",
"Pizza Hut b",
"Pizza Point b"
} ;
Deals deals;
#Override
protected void onCreate(Bundle savedInstanceState) {
// code
deals = new Deals();
deals.setArguments(bundle);
Toolbar toolbar = (Toolbar) findV
// code
}
// code
2.) Use deals inside getItem
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
MapsFragment mapsActivity=new MapsFragment();
return mapsActivity;
}
case 1: {
return deals;
}
}
return null;
}
or you can do this
#Override
public Fragment getItem(int position) {
try {
switch (position) {
case 0: {
MapsFragment mapsActivity=new MapsFragment();
return mapsActivity;
}
case 1: {
Deals deals = new Deals();
Bundle bundle = new Bundle();
bundle.putStringArray("name", check);
deals.setArguments(bundle);
return deals;
}
}
}
catch ( Exception e)
{
Log.i("okkk", "Exception 1 : " + e);
}

Querying Azure Freezes Android App

I'm trying to integrate azure's app service with my app. In particular, I'm trying to store data on the database hosted by Azure. I can insert data fine, but whenever I try to retrieve it, my app freezes.
MainActivity- starts the activity and initializes the azure connection and table.
public class MainActivity extends ActionBarActivity {
/**
* TODO: view data, put data in ordered lists, rate data, scheduler
* **/
Toolbar toolbar;
ViewPager pager;
ViewPageAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"New","Trending","Famous"};
int Numboftabs =3;
MobileServiceClient client;
MobileServiceTable<Post> postTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
//manually set action bar color since not happening before
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPageAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.colorAccent);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
postPrompt();
}
});
//initialize azure
try {
client = new MobileServiceClient("https://firechat.azurewebsites.net", this);
postTable = client.getTable(Post.class);
} catch (MalformedURLException e) {
e.printStackTrace();
}
//testing
//Post post = new Post("haha, so funny :p");
//postTable.insert(post);
}
private String makePost(String input){
Post post = new Post(input);
postTable.insert(post);
return post.text;
}
}
return post.text;
}
}
Tab1- a fragment that populates a list with data retrieved from the server. I believe my error is here when I try to query azure for the data.
public class Tab1 extends Fragment {
MainActivity mainActivity;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
#Override
public void onStart() {
super.onStart();
try {
//get data from azure
mainActivity = (MainActivity) getActivity();
List<Post> postList= mainActivity.postTable.execute().get();
//List<Post> postList = new ArrayList<Post>();
//set lists
ListView newListView = (ListView) mainActivity.findViewById(R.id.newListView);
NewAdapter newAdapter = new NewAdapter(mainActivity, postList);
newListView.setAdapter(newAdapter);
}catch(Exception e){
}
}
}
I found out I was having the error because you must retrieve data from Azure using an async task. I left an example of one down below.
private void retrievePosts(){
AsyncTask<Void,Void,Void> task = new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
postList= mainActivity.postTable.execute().get();
Log.e("TAG",postList.get(0).text);
newAdapter.updateList(postList);
} catch (final Exception e) {
}
return null;
}
};
runAsyncTask(task);
}

Tabs with Fragment life cycle

in my app i have a Tabs with fragment classes. i trying to refresh listView in "fragment a" with the new data i insert.
In "fragment b" i have EditText and Button ,that inserting text to the database.
in "fragment a" i have the ListView with the dataBase rows. when "fragment a" is "OnCreateView" i just put the dataBase on a "ArrayList" and past it to my baseAdapter.
but "onCreateView" not refreshing my new data every time i get into the "fragment a" else i goes to "fragment c" and "onDestroy" call on "fragment a".
so my result it was to call : "setUserVisibleHint" override method, and check if it is visible and refreshing the list.
but i dont think it is the good practice .
what should i do?
Class a
public class ListFragment extends Fragment{
basAdapterCustom adapter;
ListView lv;
ArrayList<Clock> list;
private DbHandler hand;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_fragment, container, false);
context = getActivity();
Log.d(TAG, "onCreateView");
hand = new DbHandler(context);
list = new ArrayList<Clock>();
lv = (ListView) v.findViewById(R.id.listOfShifts);
adapter = new basAdapterCustom(list, getActivity());
lv.setAdapter(adapter);
refreshList();
return v;
}
//like on "resume":
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
refreshList();
if (!isVisibleToUser) {
// TODO stop
}
}
}
private void refreshList() {
list = hand.getByWorkName();
adapter = new basAdapterCustom(list,getActivity());
lv.setAdapter(adapter);
}
class b:
public class ClockFragment extends Fragment{
DbHandler hand;
Context context;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.clock, container,false);
context = getActivity();
hand = new DbHandler(context);
return v;
}
// ADD to .Db
public void addToDb(View v){
hand.add(new Clock(0, dateDay));
}
}
class mainActivity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnPageChangeListener{
public static final String TAG = "myClock";
String[] tabMenu = {"FRAG A","FRAG B","FRAG C"};
private ViewPager viewPager;
private TabPagerAdapter mAdapter;
private ActionBar actionBar;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(MainActivity.TAG, "OnCreate = MainActivity (Pager");
viewPager = (ViewPager) findViewById(R.id.pager );
actionBar = getActionBar();
mAdapter = new TabPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tabsNames : tabMenu) {
actionBar.addTab(actionBar.newTab().setText(tabsNames).setTabListener(this));
}
viewPager.setOnPageChangeListener(this);
}
// public void transDialog(){
// Dialog mDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
// }
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}
PagetAdapter.class
public class TabPagerAdapter extends FragmentPagerAdapter {
private static final String TAG = "myClock";
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int index) {
Log.d(TAG, " CLASS : TabPagerAdapter");
switch (index) {
case 0:
return new ListFragment();
case 1:
return new ClockFragment();
case 2:
return new SettingFragment();
default:
break;
}
Log.d(TAG, " CLASS : TabPagerAdapter = "+index);
return null;
}
#Override
public int getCount() {
return 3;
}
}
Please help me i hope you are understand my problem...
You want to update listView in fragment A, after insert data in fragment b? Then  you have a few solutions to choose:
1. Implement communications between fragments via activity. Then B insert date, it send message to activity, that data need to be updated. Then fragment A started, it's ask activity to need update data. For details on implementing this communication check link.
2. Use some bus library, EventBus for example. Then fragment B insert data, it post 'data changed' event to bus. Fragment A checks on start if this event occurs.
3. Use Loaders which "monitor the source of their data and deliver new results when the content changes."

Categories

Resources