I have an activity with fragment pager and I want to know how to call an asynctask located on that activity from fragment .
AddActivity.java
public class AddActivity extends FragmentActivity {
ViewPager vp;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
vp = (ViewPager) findViewById(R.id.pager);
PagerAdapter pa = new FragPagerAdapter(getSupportFragmentManager());
vp.setAdapter(pa);
}
//This void to get All field from the differents fragments and put them into jsonObject
protected JSONObject createJsonObjectVR () {
...
}
// Call the Post Method
public class addVR extends AsyncTask<String, String, String> {
...
}
OtherFragment.java
public class OtherFragment extends Fragment {
Button btn;
public OtherFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_other, container, false);
btn = (Button) view.findViewById(R.id.send);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Here I want to call the createVR asynctask in the parent Activity
}
});
return view;
}
}
FragPagerAdapter
public class FragPagerAdapter extends FragmentPagerAdapter {
public FragPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// First Fragment The main
return new FirstFragment();
case 1:
// Milk (Second) fragment activity
return new SecondFragment();
case 2:
// Housing (Third) fragment activity
return new HousingFragment();
case 3:
//Feeding (fourth) fragment activity
return new FeedingFragment();
case 4:
// Other (Fith the last) fragment activity
return new OtherFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 5;
}
}
in your fragment :
((AddActivity) getActivity()).someMethodToCallAsyncTaskInAddActivity();
inf your AddActivity:
public void someMethodToCallAsyncTaskInAddActivity() {
new AsyncTask(someOptions_if_needed).execute();
}
One more option
public static class ASyncronius extends AsyncTask<Void, Void, Void>
if you make it static you can call this async task from anywhere
AddActivity.ASyncronius abs = new AddActivity.ASyncronius ();
abs.execute()
Edit 2014-11-11
if you use fragment in diffrent activitys, then you shuld make shure, that those activitys extends same master class, that contains async method.
class ParentActivity extends Activity {
someMethodToCallAsyncTaskInParentActivity(){
***new async execute***
}
public class async extends AsyncTask<void, void, void>{
***Some stuff***
}
}
Then:
class FirstActivity extends ParentActivity{
}
also
class SecondActivity extends ParentActivity{
}
in your fragment
((ParentActivity)getActivity()).someMethodToCallAsyncTaskInParentActivity();
or if you dont need in that other activity use async task, then just do some thing like this:
try{
((FirstActivity)getActivity()).someMethodToCallAsyncTaskInParentActivity();
} catch( Exception e) {
// this is not needed activity
}
Related
I'm trying to use View Pager with Fragment State Adapter. But getting a NullPointerException when trying to invoke a Fragment method after creating its instance.
Here is the activity class and Adapter class:
public class AddScheduleActivity extends AppCompatActivity {
private FragmentOverview fragmentOverview;
private FragmentTodo fragmentTodo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_schedule);
ViewPager2 viewPager = findViewById(R.id.viewPager_AddScheduleActivity);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), getLifecycle()));
fragmentOverview = new FragmentOverview();
fragmentOverview.setTargetView(); //ERROR IS HERE
My view pager adapter is:
private class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return fragmentOverview;
case 1:
return fragmentTodo;
default:
return null;
}
}
#Override
public int getItemCount() {
return 2;
}
}
My FragmentOverView class is:
public class FragmentOverview extends Fragment{
private FrameLayout mTargetFrameLayout;
private FrameLayout mDescriptionFrameLayout;
public FragmentOverview() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_overview, container, false);
mDescriptionFrameLayout = rootView.findViewById(R.id.descriptionView_frameLayout_OverviewFragment);
mTargetFrameLayout = rootView.findViewById(R.id.targetView_frameLayout_OverviewFragment);
return rootView;
}
public void setTargetView() {
mTargetFrameLayout.removeAllViews();
if (progress.maxProgress != null) {
//ADD A CHILD VIEW
mTargetFrameLayout.setVisibility(View.VISIBLE);
} else mTargetFrameLayout.setVisibility(View.GONE);
}
}
But when I call the setTargetView() method after creating instance of FragmentOverview, I'm getting a NullPointerException. From log I noticed that the mTargetFrameLayout is null.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.FrameLayout.removeAllViews()' on a null object reference
I think this is because the activity lifecycle methods onCreate(), onStart(), onResume() are called before the fragment lifecycle methods onCreate() & onCreateView(). But how to overcome this problem? Or am I trying to do in a wrong way?
I think your assumption is right. The fragment layout is generated in onViewCreated() of FragmentOverview class. But this method start executing after the Activity lifecycle methods onCreate(), onStart() and onResume() are executed. You can checkout the lifecycle relation of Activity and Fragment by overwriting lifecycle methods and adding logs as mentioned by #Max_Hockeborn.
So you will always get the views i.e mTargetFrameLayout null if you call setTargetView() before executing onCreateView() in FragmentOverview.
To solve this, you can add a callback method that will be executed in parent class after executing the onCreateView() of FragmentOverveiw. And in that callback you can invoke setTargetView().
Here I'm providing a possible solution for your case:
In FragmentOverview add this lines:
public class FragmentOverview extends Fragment{
//all your fields;
private OverviewCallbacks callbacks;
public FragmentOverview(OverviewCallbacks callbacks) {
this.callbacks = callbacks;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//inflate the rootView and find all the childViews;
//I think your codes are okey;
}
//Overwrite this method;
//You can also overwrite onViewCreated() lifecycle method;
//And add call this callback method from here;
#Override
public void onResume() {
super.onResume();
callbacks.onReach();
}
public void setTargetView() {
//Do what you want to do;
}
public interface OverviewCallbacks {
void onReach();
}
}
Thats all for FragmentOverView class.
Now modify your Activity class as follows:
public class AddScheduleActivity extends AppCompatActivity {
private FragmentOverview fragmentOverview;
private FragmentTodo fragmentTodo;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Your codes
fragmentOverview = new FragmentOverview(new FragmentOverview.OverviewCallbacks() {
#Override
public void onReach() {
setTargetView();
}
});
}
}
Hope this will work. Comment if anything gone wrong.
This is just a fast idea that I couldn't test yet.
You could try to change this:
public class AddScheduleActivity extends AppCompatActivity {
private FragmentOverview fragmentOverview;
private FragmentTodo fragmentTodo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_schedule);
ViewPager2 viewPager = findViewById(R.id.viewPager_AddScheduleActivity);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), getLifecycle()));
fragmentOverview = new FragmentOverview();
fragmentOverview.setTargetView(); //ERROR IS HERE
to this:
public class AddScheduleActivity extends AppCompatActivity {
private FragmentOverview fragmentOverview = new FragmentOverview();
private FragmentTodo fragmentTodo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_schedule);
ViewPager2 viewPager = findViewById(R.id.viewPager_AddScheduleActivity);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), getLifecycle()));
fragmentOverview.setTargetView(); //ERROR IS HERE
To check your assumption that your problem is based on the call order you can add some logs and check the order they are called in with Logcat (given you use android studio)
Something like this:
public class AddScheduleActivity extends AppCompatActivity {
private FragmentOverview fragmentOverview;
private FragmentTodo fragmentTodo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_schedule);
ViewPager2 viewPager = findViewById(R.id.viewPager_AddScheduleActivity);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), getLifecycle()));
Log.d("YOUR_TAG","Activity onCreate 1");
fragmentOverview = new FragmentOverview();
fragmentOverview.setTargetView(); //ERROR IS HERE
and
public class FragmentOverview extends Fragment{
private FrameLayout mTargetFrameLayout;
private FrameLayout mDescriptionFrameLayout;
public FragmentOverview() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_overview, container, false);
mDescriptionFrameLayout = rootView.findViewById(R.id.descriptionView_frameLayout_OverviewFragment);
mTargetFrameLayout = rootView.findViewById(R.id.targetView_frameLayout_OverviewFragment);
Log.d("YOUR_TAG","FragmentOverview onCreateView 1");
return rootView;
}
public void setTargetView() {
Log.d("YOUR_TAG","FragmentOverview setTargetView 1");
mTargetFrameLayout.removeAllViews();
if (progress.maxProgress != null) {
//ADD A CHILD VIEW
mTargetFrameLayout.setVisibility(View.VISIBLE);
} else mTargetFrameLayout.setVisibility(View.GONE);
}
}
The last one could be interesting for you to see if onCreateView (and the initiation of the variables that cause your problems) is finished before the setTargetView() function is called.
I have an Activity. When I click on the button, I want to run the method in Fragment. But it does not work. I tried many ways, but I could not get it working.
My Activity;
public class MyActivity extends Activity {
Button button;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity_main);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("First"));
tabLayout.addTab(tabLayout.newTab().setText("Second"));
viewPager= (CustomViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
button = (Button)findViewById(R.id.button);
button .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyFragment firstfragment = (MyFragment ) getFragmentManager().findFragmentByTag(“tab1”);
firstfragment.MyMethod();
}
});
}
}
MyFragmentAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.webviewapp.Fragment.PromotionFragment;
import com.webviewapp.Fragment.WebFragment;
public class MyFragmentAdapter extends FragmentPagerAdapter {
int tabCount;
public MyFragmentAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FirstFragment tab1 = new FirstFragment ();
return tab1;
case 1:
SecondFragment tab2 = new SecondFragment ();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
FirstFragment
public class FirstFragmentextends Fragment {
Button fragmentbutton;
public FirstFragment() {
// Required empty public constructor
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_web, container, false);
fragmentbutton = (Button) view.findByViewId(R.id.fragmentbutton );
}
public void MyMethod(){
fragmentbutton.setVisibility(View.GONE);
}
}
I'm sorry to cause confusion. What I'm trying to do is to run MyMethod when I press the button in Activity. MyMethod is a special method in the fragment. I apologize again for not being able to add the codes at first.
If you want to call a method from FirstFragment
FirstFragment firstFragment = (FirstFragment) getSupportFragmentManager().getFragments().get(0);
firstFragment.MyMethod();
If you want to call a method from SecondFragment
SecondFragment secondFragment = (SecondFragment) getSupportFragmentManager().getFragments().get(1);
secondFragment.MyMethod();
The index 0 or 1 based on position in getItem method of your adapter.
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FirstFragment tab1 = new FirstFragment();
return tab1;
case 1:
SecondFragment tab2 = new SecondFragment();
return tab2;
default:
return null;
}
}
Then give it a try.
You use FragmentManager to get a handle on the fragment.
You are making a new instance of a Fragment in your code:
final FirstFragment firstfragment= new FirstFragment ();
Where that new object is not bound to any activity.
FragmentManager
Too late for answering the question but this is a easy way to get fragment instance and call methods in a fragment; you have to get instance of your fragment then call your public method:
In your fragment :
private static yourFragment instance;
then in onCreateView of your fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
instance= this;
View v = inflater.inflate(R.layout.fragment_tools, container, false);
binding = FragmentToolsBinding.inflate(inflater, container, false);
return v;
}
and also in your fragment you have to have a static method that returns the instance:
public static yourFragment GetInstance()
{
return instance;
}
then you have a public method in in your fragment that you want to call it like this:
public void theMethod()
{
Toast.makeText(getActivity(), "Test", Toast.LENGTH_SHORT).show();
}
then you can get fragment instance and call your non static public method like this:
yourFragment frag = yourFragment.GetInstance();
frag.theMethod();
I am trying to use multiple Fragments on an Activity. What I am doing is:
1. Add the first Fragment to the Activity. The first Fragment contains a button at the bottom of the screen.
2. Replace it with the second Fragment by adding it to the backstack.
When I click on the button on the bottom of the first Fragment, it automatically slides up (I don't know why) and moves to second Fragment:
When I go back to the first Fragment by pressing the back button, the button in the first Fragment goes out of view:
MainActivity
public class MainActivity extends AppCompatActivity implements UserDetailsFragment.UserDetailsFragmentListener,
PhotoFragment.PhotoFragmentListener, TestFragment.TestFragmentListener{
#Bind(R.id.container)
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
ButterKnife.bind(this);
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
initView();
}
private void initView() {
TestFragment testFragment = new TestFragment();
FragmentUtil.replaceFragment(this,R.id.container, testFragment);
}
#Override
public void onProfileDetailCompleted(UserModel userModel) {
PhotoFragment photoFragment = PhotoFragment.newInstance(userModel);
FragmentUtil.replaceFragment(this, R.id.container, photoFragment);
}
#Override
public void onPhotoUploaded(UserModel userModel) {
}
#Override
public void onSkipPhotoClicked() {
PhotoFragment photoFragment = PhotoFragment.newInstance(null);
FragmentUtil.replaceFragment(this, R.id.container, photoFragment);
}
#Override
public void onTest() {
PhotoFragment photoFragment = PhotoFragment.newInstance(null);
FragmentUtil.replaceFragment(this, R.id.container, photoFragment);
}
}
TestFragment.java
public class TestFragment extends BaseFragment {
public TestFragment() {
// Required empty public constructor
}
public interface TestFragmentListener {
void onTest();
}
private TestFragmentListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_test, container, false);
ButterKnife.bind(this, view);
return view;
}
#OnClick(R.id.next_btn)
public void onNextButtonClicked() {
//TODO validate view
if(mListener!=null)
mListener.onTest();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof TestFragmentListener) {
mListener = (TestFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement TestFragmentListener");
}
}
}
FragmentUtils.java
public class FragmentUtil {
public static boolean hadFragment(AppCompatActivity activity) {
return activity.getSupportFragmentManager().getBackStackEntryCount() != 0;
}
public static void replaceFragment(AppCompatActivity activity, int contentId, BaseFragment fragment) {
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out);
if (hadFragment(activity)) {
transaction.replace(contentId, fragment, fragment.getClass().getSimpleName());
} else {
transaction.add(contentId, fragment, fragment.getClass().getSimpleName());
}
transaction.addToBackStack(null);
transaction.commit();
}
public static void removeFragment(AppCompatActivity activity, BaseFragment fragment) {
activity.getSupportFragmentManager().beginTransaction()
.remove(fragment)
.commit();
}
public static void showFragment(AppCompatActivity activity, BaseFragment fragment) {
activity.getSupportFragmentManager().beginTransaction()
.show(fragment)
.commit();
}
public static void hideFragment(AppCompatActivity activity, BaseFragment fragment) {
activity.getSupportFragmentManager().beginTransaction()
.hide(fragment)
.commit();
}
public static void attachFragment(AppCompatActivity activity, BaseFragment fragment) {
activity.getSupportFragmentManager().beginTransaction()
.attach(fragment)
.commit();
}
public static void detachFragment(AppCompatActivity activity, BaseFragment fragment) {
activity.getSupportFragmentManager().beginTransaction()
.detach(fragment)
.commit();
}
}
If I move from the second Fragment to the third Fragment (which is the same as the first), the button on the bottom of the second screen will look fine. But the button on first Fragment still goes out of the view. The problem only exists in the view of the first Fragment. Please help.
i had somewhat similar issue. I was using the appcompact theme and my bottom layout was going out of the screen when i replace fragment. Then I tried different theme after that it worked perfectly fine. So if your are also using app compact theme then try any other theme. Hope so it will solve your problem.
I m new to android and i m having trouble with fragment communication, reading about it discovered the standard method of creating an interface and implementing it from the parentActivity which doesn't work in my case which is as follows.
I have an Activity named as ActivityA which extends fragment activity,in which i have a view pager for i want to keep two fragments namely fragmentA and fragmentB which should be swipable fragments.
fragmentA has a button which onClicked should make a change in fragmentB, to be precise on click it should add a string in the listView in fragmentA.
Now i have created the both the fragments's layouts as well as added the viewPAger to my FragmentActivity, they work great on swiping, the function is executed onButtonClick of fragmentA and logic works perfectly, after this is i want the changes to be reflected in fragmentB.
Using the interface method i can't find the reference to my fragment by id as it is added by viewPager to ActivityA
How do i do this??
help me out.
Stackoverflow says don't ask questions with out code so
Here is the Sample code
Activity A which has a virewPAger, need help how to get my fragment's Reference from the viewPager
public class ActivityA extends FragmentActivity implements FragmentA.Communicator
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_A);
viewPager= (ViewPager) findViewById(R.id.pager);
fragmentManager=getSupportFragmentManager();
viewPager.setAdapter(new myAdapter(fragmentManager));
}
class myAdapter extends FragmentPagerAdapter{
public myAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
switch (i){
case 0: fragment = new listOfIDsScanned();
break;
case 1: fragment = new displayCounter();
break;
default: //something witch won't crush the app
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
This is fragmentA , actual fragment name is something else just for simple representation calling it fragmentA, which has an interface Communicator to communicate between fragments
public class fragmentA extends android.support.v4.app.Fragment implements View.OnClickListener
{
TextView counter;
Button scanStudentID;
int count=0;
String name=null,rollNo=null;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.display_counter,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
scanStudentID= (Button) getActivity().findViewById(R.id.startScanning);
scanStudentID.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch(v.getId()){
case R.id.startScanning:
startScanning();
break;
}
}
public void startScanning()
{
startActivityForResult(new Intent(getActivity(),Barcode.class),1);
}
public interface Communicator
{
// necessary methods
}
}
now finally fragmentB, in which methodToBeCalled(parameters) has to be invoked on the button click in fragementA
public class fragementB extends android.support.v4.app.Fragment
{
ListView listView;
ArrayList<String> rollNo= new ArrayList<>();
ArrayList<String> studentName= new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_of_ids_scanned,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView= (ListView) getActivity().findViewById(R.id.listView);
}
public void methodToBeCalled(String rollNo,String studentName)
{
if(!alreadyScanned(rollNo))
{
}
else
{
}
}
boolean alreadyScanned(String rollNo)
{
return true;
}
}
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."