Android, cardflip animation, fragments not displaying - android

I am having issues with the cardflip animation in Android. I am following their guide and also trying to pick a part the AnimationsDemo to try to understand this. But I have created all the card flip in and outs in XML and the card front and back layout in XML. I keep getting an error message when I try to add the fragment in onCreate. I'm not sure what is triggering the error as the code looks like the example code they use. I've included the error message and jave code below. Thanks for your time.
public class MainActivity extends ActionBarActivity {
/**
* Whether or not we're showing the back of the card (otherwise showing the front).
*/
private boolean mShowingBack = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
}else {
mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);
}
/**
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
*/
}
private void flipCard() {
if (mShowingBack) {
getFragmentManager().popBackStack();
return;
}
// Flip to the back.
mShowingBack = true;
// Create and commit a new fragment transaction that adds the fragment for the back of
// the card, uses custom animations, and is part of the fragment manager's back stack.
getFragmentManager()
.beginTransaction()
// Replace the default fragment animations with animator resources representing
// rotations when switching to the back of the card, as well as animator
// resources representing rotations when flipping back to the front (e.g. when
// the system Back button is pressed).
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
// Replace any fragments currently in the container view with a fragment
// representing the next page (indicated by the just-incremented currentPage
// variable).
.replace(R.id.container, new CardBackFragment())
// Add this transaction to the back stack, allowing users to press Back
// to get to the front of the card.
.addToBackStack(null)
// Commit the transaction.
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
/**
* A fragment representing the front of the card.
*/
public static class CardFrontFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_front, container, false);
}
}
/**
* A fragment representing the back of the card.
*/
public static class CardBackFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_back, container, false);
}
}
}
Error:
The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MainActivity.CardFrontFragment) MainActivity.java /Lab6b/src/you/ca/mohawk/lab6b line 28 Java Problem

It seems issue should be with your Fragment import.
If you are using fragment support library then
import android.support.v4.app.Fragment;
and fragment manager instance should be get as
getSupportFragmentManager()
Else if your using the default Fragment then change the import as
import android.app.Fragment;

Related

Error No suitable method found for add(int, Fragment)

I was trying to inflate a fragment in an Activity and here is the code.
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container2, new DetailFragment())
.commit(); //Line with Error
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is my DetailFragment class
/**
* A placeholder fragment containing a simple view.
*/
public class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
return rootView;
}
}
Here goes the layout for fragment_detail
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textSize="18sp"
android:id="#+id/fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The error I am facing is cannot resolve method 'add(int,com.example...DetailFragment)'. As, I am beginner to android, please also guide me on how should I go about, tackling such type of errors.
Your DetailFragment need to extends from android.support.v4.app.Fragment instead of Fragment. Something like this
public class DetailFragment extends android.support.v4.app.Fragment {
......
}
Make sure your DetailFragment uses the fragment from the version 4 support library and
import the library below into your fragment class. The problem is that you are using android.app.fragment instead of android.support.v4.app.Fragment.
import android.support.v4.app.Fragment;
public class DetailFragment extends Fragment{
}

getting nullPointerException when trying to call fragment method in my Activity?

I am trying to do something relatively basic by drawing a circle on a fragments layout when the app user presses down on the screen. essentially drawing a small circle on the area of the screen where a user presses. So i started with a basic project with a fragment in the main layout.I have a gestures class that extends simpleOnGestureListener. this returns the coordinates for my circle to the main activity. this works fine. but in my onTouchEvent method in the main activity when i call frag.drawCircle() i get a nullpointerexception and I am not too sure why this is. below is the code for my MainActivity. i think I am doind everything correctly including getting the fragment using the fragmentmanager and using its "tag" to retrieve the fragment? below is the code for my main class.
public class Circles extends Activity {
private GestureDetector detector;
private PlaceholderFragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circles);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.activitylayout, new PlaceholderFragment(),"myfrag")
.commit();
}
detector = new GestureDetector(this, new Gestures());
FragmentManager manager = getFragmentManager();
frag = (PlaceholderFragment) manager.findFragmentByTag("myfrag");
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
boolean consumed = detector.onTouchEvent(event);
float x = Gestures.x;
float y = Gestures.y;
if(consumed)
{
Log.d("consumed? ", String.valueOf(consumed));
Log.d("x : ", String.valueOf(x));
Log.d("y : ", String.valueOf(y));
frag.drawCircle();
}
return super.onTouchEvent(event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.circles, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_circles, container, false);
return rootView;
}
public void drawCircle()
{
Log.d("stuff", "draw circle here!");
}
}
}
obviously the fragments isn't being instantiated properly. I am just not too sure why that is at present. any help is greatly appreciated.
Override onResume method and try moving this code in onResume
FragmentManager manager = getFragmentManager();
frag = (PlaceholderFragment) manager.findFragmentByTag("myfrag");
A better solution will be doing everything in onCreate(). Doing in onResume will just destroy the meaning of having onCreate and moreover just confuse the control flow if reference of that fragment is required before the execution of onResume.
Instread of putting everything in one statement, just break it and make it fit your need.
Here is the code
private PlaceholderFragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circles);
if (savedInstanceState == null) {
frag = new PlaceHolderFragment();
getFragmentManager().beginTransaction()
.add(R.id.activitylayout, frag ,"myfrag")
.commit();
}else{
FragmentManager manager = getFragmentManager();
frag = (PlaceholderFragment) manager.findFragmentByTag("myfrag");
}
detector = new GestureDetector(this, new Gestures());
}
This way you wont have issue getting a null reference. Since if activity is recreated the Fragment will be in backstack so you can retrieve it by tag. But if activity is being created forthe first time then first get reference and then commit the transaction.

Error. .commit() in Fragments in onCreate method

So, here's myActivity.java
Basically, I'm getting an error in onCreate method when I'm trying to use .commit()
So, just unsure of why is that. Could use some guidance. Thanks!
Also, a beginner with Fragments so, gets me a little puzzled from time to time.
It shows me that it "Cannot resolve method commit()".
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment()
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A Forecast fragment containing a simple view.
*/
public static class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
String[] forecastArray={
"Right Now - Hot. Grab a Lemonade!",
"Today - Boiling! Feels more like a Heat Furnace!",
"Tomorrow - Rains! Carry an Umbrella!",
"Tuesday - Hailstones!",
"Wednesday - Stormy",
"Thursday - Snowfall!",
"Friday - Rebecca Black",
"Saturday - Thunder!",
"Sunday - Just right." };
List<String>weekForecast=new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
ListView listView=(ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
}
}
This is wrong
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment().
commit()); //<-----
}
commit() is a method on the FragmentTransaction, not on the Fragment. So change your code to this:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment())
.commit();
}
If you're getting confused with fragments confused you shouldn't be concatenating all these things, do em in seperate lines until you're fully comfortable:
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment()
.commit();
becomes
ForecastFragment newFragment = new ForecastFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.container, newFragment );
transaction.addToBackStack(null);
transaction.commit();

Pressing back does not return to previous fragment

I have a problem with adding the fragment transactions to the back stack. I have a Main activity in which I populate my layout with a Menu Fragment:
public class MainActivity extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().add(R.id.frag_container, new MainMenuFragment()).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then, inside the MainMenuFragment, the user chooses some option which results in replacing the menu fragment with some other fragment:
public class MainMenuFragment extends Fragment implements OnItemClickListener{
GridView grid;
FragmentManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.main_menu_fragment, container, false);
manager = getActivity().getFragmentManager();
grid = (GridView) root.findViewById(R.id.gridView1);
grid.setAdapter(new MenuTileAdapter(getActivity()));
grid.setOnItemClickListener(this);
return root;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction trans = manager.beginTransaction();
if (position == 0){
trans.replace(R.id.frag_container, new BasicSettingsFragment());
trans.addToBackStack(null);
trans.commit();
}
}
}
For what i understand, this should make it so that when the user presses back button on their device, they will be brought back to the menu fragment, but instead this quits the app. What am i doing wrong?
In your Activity overwrite:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
And probably you need to use in every commited fragment transaction:
FragmentTransaction.addToBackStack(null);
Your code is a mixup, you use ActionBarActivity from appcompat and not using getSupportFragmentManager() and the fragments import should be the appcompat one if you decide to use it. If not, use Activity instead of ActionBarActivity and the simple Fragment import with FragmentManager
Add this to your activity android:configChanges="keyboardHidden|orientation|screenSize"
This will stop your activity from restarting when you rotate.
use setRetainInstance(true) on fragments.
You are not adding the MainMenuFragment to the back stack. You can try this one on your activity:
getFragmentManager().beginTransaction().add(
R.id.frag_container, new MainMenuFragment()).
addToBackStack(null).commit();
When you add or replace a fragment with the FragmentManager, you need to manually add the old fragment to the backstack with addToBackStack() before calling commit().

How to remove the fragments so it wont appear in the next activity?

So i've just started doing some android programing, and I'm already stuck! My problem is; I want want my fragment, from MainActivity, to NOT be a part of my new Activity. I want the activity to be all blank, the fragment from MainActivity should be gone, buuut it's not.
The content from the "fragmentz" xml document, which is "linked" in the Fragment Class. Should NOT appear in the second Activity... Where in the SecondActivity have I associated it with the Fragment Class? This is getting frustrating :D
So here is my MainActivity code:
public class MainActivity extends ActionBarActivity {
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
manager= getSupportFragmentManager();
ArticleFragment frag = new ArticleFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction = manager.beginTransaction();
transaction.add(R.id.fragmentet,frag,"tagg");
transaction.commit();
// here the Fragment should be added to my MainActiviy
}
public void WalkForward(View view)
{
ArticleFragment frag = (ArticleFragment) manager.findFragmentByTag("tagg");
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(frag);
transaction.commit();
// Here, the fragment should disappear before the new activity start
Intent intenten = new Intent(this, SecondActivity.class);
startActivity(intenten);
// Start new activity
finish();
// I've tried this finish method, and also onDestroy and so on... But that work either. I thought the Fragments should
// disappear with its activity?
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
My Fragment Class:
public class ArticleFragment extends Fragment {
public void onAttach(Activity activity)
{
Log.d("Fraggment", "onAttach");
super.onAttach(activity);
// #17 Android FragmentTransaction Part 2: Android Application Development Development [HD 1080p]
}
public void onCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onCreate");
super.onCreate(saveInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentz, container, false);
}
public void onActivityCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onActivityCreated");
super.onActivityCreated(saveInstanceState);
}
public void onPause()
{
super.onPause();
Log.d("Fraggment", "onPause");
}
public void onStop()
{
super.onStop();
Log.d("Fraggment", "onStop");
}
public void onDestroyView()
{
super.onDestroyView();
Log.d("Fraggment", "onDestroyView");
}
public void onDestroy()
{
super.onDestroy();
Log.d("Fraggment", "onDestroy");
}
public void onDetach()
{
super.onDetach();
Log.d("Fraggment", "onDetach");
}
And my Second Activity Class:
public class SecondActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second,
container, false);
return rootView;
}
}
}
I hope you understand what I mean :P Is there anything I can do? Thanks in advance!
Remove this
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
from your Second Activity. And why are you extending MainActivity? Some Reason?

Categories

Resources