Constructor within activity is undefined - java

I have been fighting with this error for a couple of hours and I am not able to continue. I need your help here!
I am trying to replace my previous TabNavigation at ActionBar by a ViewPager in SDK21, looking at comments within StackOverflow I found this webpage, where the use of PagerTabStrip is described with an example, so I tried to implement it in my activity, however I am getting an strange error.
I tried to google the problem and all the suggestions are not really applicable to my problem (wrong parameters in the constructor are the usual errors) . I also reproduced the error with a simple Activity in order to avoid anything I have in my previous activity, but the error keeps. I attach you here the code I replicated isolated:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestActivity extends Activity {
CustomPagerAdapter mCustomPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adding_users_to_list);
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), this.getApplicationContext());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomPagerAdapter);
}
class CustomPagerAdapter extends FragmentPagerAdapter {
Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// Create fragment object
Fragment fragment = new DemoFragment();
// Attach some data to the fragment
// that we'll use to populate our fragment layouts
Bundle args = new Bundle();
args.putInt("page_position", position + 1);
// Set the arguments on the fragment
// that will be fetched in the
// DemoFragment#onCreateView
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + (position + 1);
}
}
class DemoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout resource that'll be returned
View rootView = inflater.inflate(R.layout.fragment_users, container, false);
// Get the arguments that was supplied when
// the fragment was instantiated in the
// CustomPagerAdapter
Bundle args = getArguments();
((TextView) rootView.findViewById(R.id.text_option)).setText("Page " + args.getInt("page_position"));
return rootView;
}
}
}
I am getting in the call to the constructor the following error:
"The constructor TestActivity.CustomePageAdapter(FragmentManager, Context) is undefined"
In here:
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), this.getApplicationContext());
I have tried to introduce the Adapter outside and inside the activity definition and is still not working. Is likely to be something simple, but... I can't see it and I need other eyes. Any idea what I am doing wrong?

change the import of the activity to:
import android.support.v4.app.FragmentActivity;
Also change constructor to:
mCustomPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), this.getApplicationContext());

The reason is that your activity is used from the ADT:
import android.app.Activity;
and the Fragments used from the support package:
import android.support.v4.app.FragmentManager;
change the import of the activity to:
import android.support.v4.app.FragmentActivity;

Related

I get this error when I run the app on my device [duplicate]

This question already has answers here:
I'm having problems with running the code on my device [duplicate]
(3 answers)
Closed 4 years ago.
I am currently getting these errors when running my code on a device
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 9401
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:46)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
now based on what I see here are the libraries for the code its stating in the error. Please help im a beginner
Events.java
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.FragmentManager;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events,
container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View
view, int position, long id) {
Intent intent = new Intent(view.getContext(),
AddEvent.class);
Uri currentVehicleUri =
ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton)
getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),
AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity
context
EventContract.EventEntry.CONTENT_URI, // Provider
content URI to query
projection, // Columns to include in the
resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
Fragment Java(it says im getting an error around here:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
if (mHost != null) {
writer.print(prefix); writer.print("mHost=");
writer.println(mHost);
}
if (mParentFragment != null) {
writer.print(prefix); writer.print("mParentFragment=");
writer.println(mParentFragment);
In conclusion I'm trying to run the app but everytime I go into a certain section, in this case being Events.java being nav_events.xml layout, I keep getting the error and don't know how to fix it
Your error is found on line 46 of your Events.java file.
You're inflating a view and declaring it a ListView in Java (on line 46) when it seems to be a LinearLayout in your XML file.
Also right after that you're using getView(). You can only use that function correctly after onCreateView() has returned a View, definitely not within it.
EDIT after comment:
You haven't returned the View yet as you can't execute any code after a return statement.
Now without your layout file I can only speculate but probably replace
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
with
View rootView = (LinearLayout) inflater.inflate(R.layout.nav_events, container, false);
Then replace all occurrences of getView() in that code block with rootView.
And at the very end
return rootView;

Toolbar in Fragment crashes app on launch

This seems like a common issue with lots of accepted answers but none of them seem to be working for me.
Most answers suggest using this piece of code to add a toolbar into a fragment:
mToolbar = (Toolbar)rootView.findViewById(R.id.toolbar);
if (mToolbar != null) {
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
}
Alas, this still crashes my app even though I'm using AppCompatActivity. I think the error may lie in the fact that my Fragment class extends Fragment and not AppCompatActivity but I don't know enough about android as of yet to be sure of this. It crashes on the setSupportActionBar line.
My Fragment code:
package erikligai.ribbitapplication;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by erik on 2017-06-07.
*/
public class MessageFragment extends Fragment {
Toolbar mToolbar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// return inflater.inflate(R.layout.message_fragment_layout, container, false);
View rootView = inflater.inflate(R.layout.message_fragment_layout, container, false);
mToolbar = (Toolbar)rootView.findViewById(R.id.toolbar);
if (mToolbar != null) {
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
}
return rootView;
}
Would appreciate any suggestions.
You need to cast your activity from getActivity() to AppCompatActivity
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();
Toolbar getting from Activity, not from Fragment
mToolbar = (Toolbar)rootView.findViewById(R.id.toolbar);

Unable to pass intent in custom array adapter

I am unable to pass an intent in this case. Nothing is displayed on the screen or Logs from the movie_detail.java. I cannot figure out hat is wrong, please help!
MainActivityFragment.java
package com.example.coderahul.a9to12;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.Arrays;
public class MainActivityFragment extends Fragment {
private movieListAdapter movieListA;
MovieList[] movieLists = {
new MovieList("Cupcake - 1.5", "/is6QqgiPQlI3Wmk0bovqUFKM56B.jpg", "368596"),
new MovieList("Donut - 1.6", "/cGOPbv9wA5gEejkUN892JrveARt.jpg", "209112"),
new MovieList("Eclair - 2.0-2.1", "/9KQX22BeFzuNM66pBA6JbiaJ7Mi.jpg", "47933"),
new MovieList("Froyo - 2.2-2.2.3", "/z09QAf8WbZncbitewNk6lKYMZsh.jpg", "127380"),
new MovieList("GingerBread - 2.3-2.3.7", "/5N20rQURev5CNDcMjHVUZhpoCNC.jpg", "271110"),
new MovieList("Honeycomb - 3.0-3.2.6", "/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg", "135397"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg", "258489"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/tSFBh9Ayn5uiwbUK9HvD2lrRgaQ.jpg", "262504"),
new MovieList("Honeycomb - 3.0-3.2.6", "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", "87101"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/zSouWWrySXshPCT4t3UKCQGayyo.jpg", "293660"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/MZFPacfKzgisnPoJIPEFZUXBBT.jpg", "76341"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", "246655")
};
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieListA = new movieListAdapter(getActivity(), Arrays.asList(movieLists));
// Get a reference to the ListView, and attach this adapter to it.
GridView gridView = (GridView) rootView.findViewById(R.id.movies_grid);
gridView.setAdapter(movieListA);
final Context context = getActivity();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
MovieList detail = (MovieList) movieListA.getItem(position);
Intent intent = new Intent(context, movie_detail.class)
.putExtra(Intent.EXTRA_TEXT, detail.title);
context.startActivity(intent);
Log.v("Check", detail.title);
}
});
return rootView;
}
}
movie_detail.java
package com.example.coderahul.a9to12;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class movie_detail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail, container, false);
Log.v("Check", "Inside Intent");
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(detail);
}
return rootView;
}
}
}
movieListAdapter.java
package com.example.coderahul.a9to12;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class movieListAdapter extends ArrayAdapter<MovieList> {
private static final String LOG_TAG = movieListAdapter.class.getSimpleName();
/**
* This is our own custom constructor (it doesn't mirror a superclass constructor).
* The context is used to inflate the layout file, and the List is the data we want
* to populate into the lists
*
* #param context The current context. Used to inflate the layout file.
A List of AndroidFlavor objects to display in a list
*/
public movieListAdapter(Activity context, List<MovieList> movieList) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, movieList);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The AdapterView position that is requesting a view
* #param convertView The recycled view to populate.
* (search online for "android view recycling" to learn more)
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Gets the AndroidFlavor object from the ArrayAdapter at the appropriate position
MovieList movieList = getItem(position);
// Adapters recycle views to AdapterViews.
// If this is a new View object we're getting, then inflate the layout.
// If not, this view already has the layout inflated from a previous call to getView,
// and we modify the View widgets as usual.
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_item, parent, false);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext())
.load("http://image.tmdb.org/t/p/w185//" + movieList.link)
.resize(200, 200)
.centerCrop()
.into(iconView);
TextView versionNameView = (TextView) convertView.findViewById(R.id.movie_title);
versionNameView.setText(movieList.title);
return convertView;
}
}
You will be able to get your Intent in Activity's onCreate() method not in your fragment onCreateView() method because intent will be recevied by activity and not by fragment.
To get your intent in your movie_detail activity do it like this
static String detail="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent =getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
detail = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}
After doing this you can use detail String to set Text in your textview
In your fragment class
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(movie_detail.detail);
You must attach the fragment to your activity's layout in order to make you fragment visible in your activity
in your movie_detail activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
}
Bundle extra = new Bundle();
extra.putExtra(Intent.EXTRA_TEXT,detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
DetailFragment fragment = new DetailFragment();
fragment.setArguments(extra);
fragmentTransaction.replace(android.R.id.content, fragment);
}
And in your fragment get the arguments and set the details wherever necessary

FragmentManager Error after updating from sdk 22 to 23 on Android

I'm using a FragmentPagerAdapter to create a 3 page viewpager and up until I upgraded to sdk 23 it worked fine. I am using one fragment and sending in different args depending on the getItem(position) to populate different data. After the upgrade Android isn't acknowledging one of the pages and I have to got to position 2 (page 3) and then slide back to position 0 (page 1) and then Android populates the page with the correct data. Running thru the debugger confirmed that Android skips over case 2 in the getItem function in TabAdapter.java. I am also getting
W/FragmentManager: moveToState: Fragment state for TabContentFragment{3ac2d125 #3 id=0x7f0f0097} not updated inline; expected state 3 found 2. I've been using this similar question as reference but still couldn't get it to work but I have cornered the problem down to the FragmentManager I am using. But after messing with it for hours I haven't been able to get Android to see that there are 3 pages not 2.
TabAdapter.java
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.movies.R;
import com.movies.date.LiveStatus;
import com.movies.fragments.TabContentFragment;
import com.movies.fragments.TabFragment;
import com.movies.utils.BundleKeys;
public class TabAdapter extends FragmentPagerAdapter {
private Context context;
public TabAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position) {
TabContentFragment fragment = new TabContentFragment();
Bundle args = new Bundle();
switch (position){
case 0:
args.putInt(BundleKeys.STATE_KEY, LiveStatus.EVENT_STARTED);
break;
case 1:
args.putInt(BundleKeys.STATE_KEY, LiveStatus.EVENT_NOT_STARTED);
break;
case 2:
args.putInt(BundleKeys.STATE_KEY, LiveStatus.EVENT_OVER);
break;
}
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return TabFragment.MAX_TABS;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return this.context.getString(R.string.tab_title_live);
case 1:
return this.context.getString(R.string.tab_title_upcoming);
case 2:
return this.context.getString(R.string.tab_title_replay);
default:
return null;
}
}
}
Data from bundle is pulled like this
this.state = getArguments().getInt(BundleKeys.STATE_KEY);
TabFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.movies.R;
import com.movies.adapters.TabAdapter;
public class TabFragment extends Fragment {
public static final int MAX_TABS = 3;
public static TabLayout tabLayout;
public static ViewPager viewPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate tab_layout and setup Views.
*/
View view = inflater.inflate(R.layout.tab_layout, null);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
viewPager = (ViewPager) view.findViewById(R.id.event_info_viewpager);
/**
* Set an Adapter for the View Pager
*/
viewPager.setAdapter(new TabAdapter(getFragmentManager(), getContext()));
/**
* Now , this is a workaround ,
* The setupWithViewPager doesn't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
Activity that Holds the TabFragment starts fragment like this:
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.container_view, new TabFragment()).commit();
I'm not sure if I am understanding your question correctly or not but it sounds to me like your last (third) tab isn't being created until you navigate to it.
By default, the ViewPager is limited to creating only 2 off screen views (one to the left and one to the right). Typically, apps start off in the left most tab, meaning, if you have 3 in total, the right most tab will not be created until you navigate closer to it.
You can override this in your MainActivity by using ViewPager.setOffScreenPageLimit(#) where ViewPager is actually the name of your ViewPager and # is the number of tabs you want to create from the start. In your case it sounds like you want this number to be 2.

Different behavior of android.app.Fragment and android.support.v4.app.Fragment while using backstack

I've created Activity and added a fragment to it using FragmentManeger. When i use android.app.Fragment and press the back button my application closes. When i use android.support.v4.app.Fragment and press the back button, the fragment is removed from the activity, but application is still working. I can't really understand why is that happening.
Here is the code i used:
Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.replace(R.id.content_fragment, new Fragment1())
.addToBackStack("first")
.commit();
}
}
Fragment:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
When i simply replace import in Activity and Fragment to same classes, but in the support library, the result is different...
EDIT:
I also replaced getFragemetManeger() to getSupportFragmentMeneger() and it still works different
if you're only looking to change the back behavior, you can try overriding
onBackPressed with something like:
if(backstackCount() > 0)
{
super.onBackPressed
}
The issue occured because i used android.support.v7.app.AppCompatActivity and android.app.Fragment. I should've used android.app.Fragment with android.app.Activity or AppCompatActivity with support fragment.

Categories