I am trying to call the functions frag.updateButtons() etc from within GameScreen (Main Activity) as ten times a second, the game cycles through these things and updates the variables accordingly.
The code is as it currently is. The frag.*** functions work when it is set up as a fragment, but now that I am wanting to use it as viewPager, it keeps having the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference
I am fairly new to programming and Android code, and clearly don't entirely understand fragments and viewPager etc, so any help here would be very much appreciated.
I have not included the whole code, just the code that I think is relevant to the problem. If you need more code or info, please ask me and I'll get you what you need.
Thank you
public class GameScreen extends FragmentActivity implements GameScreenFragment.FragInterface{
ViewPager mViewPager;
GameScreenFragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_screen);
mViewPager = (ViewPager) findViewById(R.id.bottomFragment);
/** set the adapter for ViewPager */
mViewPager.setAdapter(new SamplePagerAdapter(getSupportFragmentManager()));
startRepeatingTask();
//the code here calls the mainLoop() function 10 times a second
}
}
//for the fragment functions
public void displayCompany(String companyName){}
public void displayCompanyIncome(){}
public void checkTeamImage(){}
public void getCostOfEmployees(){}
public void updateButtons(){}
public void mainLoop(){
//display company name and company income in fragment
frag = (GameScreenFragment) getSupportFragmentManager().findFragmentById(R.id.bottomFragment);
frag.updateButtons();
frag.displayCompanyIncome();
frag.getCostOfEmployees();
frag.displayCompany(Global.companyName[Global.companyNumber]);
//updates the picture for that company
frag.checkTeamImage();
}
public class SamplePagerAdapter extends FragmentPagerAdapter {
public SamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
/** Show a Fragment based on the position of the current screen */
Global.companyNumber = position;
return new GameScreenFragment();
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
and then in the fragment whose ID in the .xml is bottomFragment
public class GameScreenFragment extends Fragment {
FragInterface fragStuff;
public interface FragInterface {
void displayCompany(String companyName);
void displayCompanyIncome();
void checkTeamImage();
void getCostOfEmployees();
void displayCompanyName();
void updateButtons();
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View view = inflater.inflate(R.layout.game_screen_fragment, container, false);
//other code here
return view;
}
}
Related
I have an Activity with three tabs and three Fragments. First Fragment shows the list of song titles and the second tab displays the selected song. The details of the songs is coming from a database.
I am implementing SearchView feature so that whatever search text user enters, only those songs should be displayed in the index.
This is exactly like the way phone book work in our devices.
I'm not able to understand how to refresh the first Fragment when the search query changes.
I'm basically looking for the method that I can call to refresh the first Fragment.
Got my answer here Android refresh a fragment list from its parent activity as suggested by #Prem. Works perfectly fine for me.
Its is achievable by making an interface
MainActivity.java
public class MainActivity extends Activity {
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
private FragmentRefreshListener fragmentRefreshListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btnRefreshFragment);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(getFragmentRefreshListener()!=null){
getFragmentRefreshListener().onRefresh();
}
}
});
}
public interface FragmentRefreshListener{
void onRefresh();
}}
MyFragment.java
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = null; // some view
/// Your Code
((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
#Override
public void onRefresh() {
// Refresh Your Fragment
}
});
return v;
}}
Below is the one way, you can easily do it. You just have to save the fragment instance. That's all.
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
private SparseArray<Fragment> array = new SparseArray<>();
ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
array.setValueAt(position, myFragment);
return myFragment;
}
#Override
public int getCount() {
return 3;
}
public SparseArray<Fragment> getFragmentArray() {
return array;
}
}
Then from your activity, you can get all viewpager fragment easily from adapter instance.
MyFragment fragment = (MyFragment) adapter.getFragmentArray().get(0); // get first fragment and casting it to your origin fragment
Then create a method on that fragment. Call like below:
fragment.myFragmentMethod(String myData){}
Have a nice day!
I'm creating application which has FragmentPagerAdapter with two pages.
The class for FragmentPagerAdapter looks like this
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment;
switch (i) {
case 0: fragment = new CurrentRateFragment(); break;
case 1: fragment = new HistoryFragment(); break;
default: fragment = new CurrentRateFragment(); break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
I want that some changes on first page (for example change Spinner selected item) caused changes on second page.
As I've read about Fragment communication (https://developer.android.com/training/basics/fragments/communicating.html) and understand that fragments can communicate only through Activity.
For this case I've created public interface in my first page class fragment
public interface CurrencyListener {
public void onCurrencyChanged();
}
And implement it in my Activity.
Now I can call void onCurrencyChanged in my Activity from my first page fragment.
But the problem is:
How to recreate second page fragment in my FragmentPagerAdapter?
Fragment creation operation is heavy.
1. If you recreate fragment the all the views will be created and previous Fragment needs to be garbage collected. Therefore there will extra memory.
Therefore rather than recreating the FirstPageFragment just refresh the data based on the callback received on your currencyChanged() method.
In this case, fragment will be created once and data will be updated every time the currencyChanged() method is called.
HistoryFragment Code(Fragment to be refreshed)
public class HistoryFragment extends Fragment implements MyActivity.IUpdateData{
/**
* Other method goes here
*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//
if(getActivity() instanceof /**Your Activity**/){
((/**Your Activity**/)getActivity()).setOnUpdateListener(this);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void updateData(Object object) {
//Refresh Data
}
}
Activity (Which will refresh data)
public class MyActivity extends Activity {
/**
* Other method goes here
*/
private IUpdateData dataUpdateListener;
public void setOnUpdateListener(IUpdateData listener){
dataUpdateListener = listener;
}
public void onCurrencyChanged(){
if(dataUpdateListener!=null){
dataUpdateListener.updateData(/**Update Data**/);
}
}
public interface IUpdateData{
void updateData(Object o);
}
}
I must clear that I am looking for an example or answer where I can use various differnt layout designs in a viewpager and the data in all the pages would be dynamic and all pages can be interacted by the user.
My Use Case and current approach towards the problem :
So I have got 8 different types of question types and so I have created layouts for all of them. Also I the data in the views for these layouts has to be populated via java Map that has fetched data from the sqlite DB.
But a test may contain 25 questions with different layouts out of the above 8. And for all these 25 questions I want to use a Viewpager and a Fragment that will return the required layout based on the passed question type value out of my java map.
My apporach towards this :
I have created an activity and have inflated it with a viewpager layout :
R.layout.practice_pager
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/test_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
*Activity Edited code *
public class TestActivity extends FragmentData implements FragmentData{
FragmentManager manager=getSupportFragmentManager();
private ViewPager mViewPager;
private MyFragmentPagerAdapter mMyFragmentPagerAdapter;
int PAGE_COUNT = 0;
GrePracticeTestRecord p=new GrePracticeTestRecord();
private HashMap<Integer, GrePracticeResultRecord> mPracResultMap;
public static int fragmentToReturn=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice_pager);
mViewPager = (ViewPager) findViewById(R.id.test_container);
//This function is called to fetch the data from sqlite db and fill the map with data
LoadingTestView();
PAGE_COUNT=mPracRecordMap.size();
initPager();
}
//here I initialize the pager and set the adapter to it
public void initPager()
{
p.setQUES(mPracRecordMap.get(1).getQUES());
p.setEXPL(mPracRecordMap.get(1).getEXPL());
fragmentToReturn=Integer.parseInt(mPracRecordMap.get(1).getQTYPE());
setData(p);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fList);
mViewPager.setAdapter(mMyFragmentPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
mMyFragmentPagerAdapter.notifyDataSetChanged();
p.setQUES(mPracRecordMap.get(mViewPager.getCurrentItem()+1).getQUES());
p.setEXPL(mPracRecordMap.get(mViewPager.getCurrentItem()+1).getEXPL());
setData(p);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void setData(GrePracticeTestRecord p) {
// TODO Auto-generated method stub
}
#Override
public GrePracticeTestRecord getData() {
// TODO Auto-generated method stub
return p;
}
}
My Adapter Edited code
public class MyFragmentPagerAdapter extends FragmentStatePagerAdapter{
private List<Fragment> fragments;
public MyFragmentPagerAdapter(FragmentManager fm,List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int position) {
System.out.println("value of position "+position);
return this.fragments.get(position);
}
/** Returns the number of pages */
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return MyFragmentPagerAdapter.POSITION_NONE;
}
}
Interface FragmentData
public interface FragmentData {
public void setData(GrePracticeTestRecord p);
public GrePracticeTestRecord getData();
}
TestFragment Edited code
public class TestFragment extends Fragment {
AnswerEnterListener callBack;
FragmentData fD;
Button submitAnswer;
EditText userAnswer;
TextView qText,expl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.qtype1, container, false);
}
public interface AnswerEnterListener
{
public void onInputAnswer(String ans);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
callBack=(AnswerEnterListener) activity;
fD=(FragmentData) activity;
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
qText=(TextView) getActivity().findViewById(R.id.question_text);
expl=(TextView)getActivity().findViewById(R.id.explanation_text);
qText.setText(Html.fromHtml(fD.getData().getQUES()));
expl.setText(Html.fromHtml(fD.getData().getEXPL()));
}
}
Similar to TestFragment , I have not the other fragments too. Each for a layout type.
Issues :
The first layout is repeated two times at the first time , and also when I swipe back then the position of data is misplaced.
Is this the right approach, I have been suggested by someone that you should use three fragments and update the left and right fragments with data , but this actually bounced off me. Can anyone share a good example of it or a blog.
I must clear that I am looking for an example or answer where I can
use various differnt layout designs in a viewpager and the data in all
the pages would be dynamic and all pages can be interacted by the
user.
This should be quite easy to make but you seem to have complicated this a lot. You need to do something like this:
Get the data from the database with the LoadingTestView(); function.
Initialize the ViewPager and set it's adapter. The adapter will return the proper fragment instance in the getItem() method, based on whatever criteria you have.
In the fragments, retrieve the data from the activity which should expose the data through some method.
I've made a simple example that you can find here.
I have a ListView in my activity.On clicking on the list item it invokes another activity.In that activity I have implemented ViewPager and fragments.
When it loads first time onResume() ,onCreate() and onCreateView() method called twice, if I clicks on first list item. (i.e. it loads first and second fragment view)
when I click on the any other List fragment except first then it calls onResume() ,onCreate() and onCreateView() methods three times (i.e. It loads previous and after and click view )
It is absoutely fine but I have google analytics code with which I have to track only current page so where I can put this code to load for only current page
My question is my googleAnalytics code tracs three or two pages at first time even user doesnot gone through those pages how to avoid this ?
My code is as below for fragment
public class MainListActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate()");
CustomFragmentPagerAdapter adapter = new CustomFragmentPagerAdapter();
viewPager.setAdapter(adapter);
}
}
//code for fragment adapter
public class CustomFragmentPagerAdapter extends FragmentPagerAdapter {
public CustomFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
CustomFragment customFragment = new CustomFragment();
arrayList.add(customFragment);
return customFragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
}
//code for fragment
public class CustomFragment extends Fragment{
public CustomFragment() {
super();
}
#Override
public void onResume() {
super.onResume();
Log.v(TAG, "onCreate -Resume");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.v(TAG, "onCreateView");
return myAnyView;
}
}
The problem is that the onResume() method is called for all your fragments, that is including the invisible ones.
Check gorn's answer here:
How to determine when Fragment becomes visible in ViewPager
You have to override
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Your logic
}
and do your logic in there.
I've got a problem with my android app crashing when trying to restore my fragments. I have not added any custom variables to the bundle that I'm trying to restore, It's all default. I'm using Fragments and ViewPager. See my code snippets below:
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
public int getCurrentItemPosition(Fragment fragment){
return getItemPosition(fragment);
}
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(position);
}
}
public class MyActivity extends FragmentActivity {
static final int NUM_ITEMS = 100000;
public int currentSelectedPage;
private int changeToFragmentIndex;
public DateTime midDate;
MyAdapter mAdapter;
ViewPager mPager;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diary);
MyApplication application = (MyApplication)getApplication();
application.dataController.myActivity = this;
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
int newDay = application.daysBetween(DateTime.now(), DateTime.parse(application.day.dateToShortString()));
this.currentSelectedPage = NUM_ITEMS/2+newDay;
mPager.setCurrentItem(NUM_ITEMS/2+newDay);
mPager.setOnPageChangeListener(new SimpleOnPageChangeListener(){
public void onPageSelected(int position){
currentSelectedPage = position;
ContentFragment fragment = (ContentFragment) mAdapter.instantiateItem(mPager, currentSelectedPage);
fragment.loadData();
}
});
}
}
public class ContentFragment extends Fragment {
private View v;
static final int NUM_ITEMS = 100000;
static ContentFragment newInstance(int num) {
ContentFragment f = new ContentFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null)
return null;
v = inflater.inflate(R.layout.diarycontent, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
setUserVisibleHint(true);
}
}
I receive this stackstrace:
Caused by: java.lang.NullPointerException
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:519)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:1 55)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:522)
As I have understood this may be a known problem with the support package and that one possible solution would be to use setUserVisibleHint(true) in onSaveInstanceState. But that didn't help.
Does anyone know another solution to the problem or what I've done wrong?
I have faced same type of issue once I started using ViewPager with FragmentStatePagerAdapter inside Tab.
Then I played with all forums related to this issue and break my head for two days to find out why this issue is occurred and how to resolve it but does not found any perfect solution that fulfills as per my requirement.
I got the solution as in order to avoid the NPE crash use FragmentPagerAdapter instead of FragmentStatePagerAdapter. When I replace FragmentPagerAdapter instead of FragmentStatePagerAdapter then not faced NPE crash issue but the same page is not refreshed itself for further navigation(which is my requirement).
Finally override the saveState method on FragmentStatePagerAdapter and everything working fine as expected.
#Override
public Parcelable saveState() {
// Do Nothing
return null;
}
How I reproduce this issue easily :
I am using the higher version(4.1) device and followed the below steps:
1. Go to Settings -> Developer Options.
2. Click the option "Do not keep activities".
Now I played with my app.
Before override the saveState() method each time the app is crashing due to the NPE at android.support.v4.app.FragmentManagerImpl.getFragment(Unknown Source). But after override saveState() no crash is registered.
I hope by doing so you will not having any issue.
I initially used solution suggested by #Lalit Kumar Sahoo. However, I noticed a serious issue: every time I rotated the device, the Fragment Manager added new fragments without removing the old ones. So I searched further and I found a bug report with a workaround suggestion (post #1). I used this fix and tested with my app, the issue appears to be resolved without any side-effects:
Workaround: Create custom FragmentStatePagerAdapter in project's src/android/support/v4/app folder and use it.
package android.support.v4.app;
import android.os.Bundle;
import android.view.ViewGroup;
public abstract class FixedFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
public FixedFragmentStatePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment f = (Fragment)super.instantiateItem(container, position);
Bundle savedFragmentState = f.mSavedFragmentState;
if (savedFragmentState != null) {
savedFragmentState.setClassLoader(f.getClass().getClassLoader());
}
return f;
}
}
Why exactly are you doing:
mPager.setOnPageChangeListener(new SimpleOnPageChangeListener(){
public void onPageSelected(int position){
currentSelectedPage = position;
ContentFragment fragment = (ContentFragment) mAdapter.instantiateItem(mPager, currentSelectedPage);
fragment.loadData();
}
});
This:
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(position);
}
Instantiates the fragment.
You can load data like this in the fragment :
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadData();
}