I am writing a simple app to learn Java, specifically how to manage fragment transactions.
The app has one MainActivity and three fragments (FragmentDefault, added to the MainActivity by default; and Fragments one and two, which can be added on a button click in MainActivity).
My app can handle on fragment transaction, but crashes during the second, regardless of the order of the transactions.
The MainActivity.java file is as follows:
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
transaction.replace(R.id.fragment_container, frag1);
transaction.commit();
transaction.addToBackStack(null);
}
public void openFrag2(View view) {
transaction.replace(R.id.fragment_container, frag2);
transaction.commit();
transaction.addToBackStack(null);
}
}
with .XML file:
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
transaction.replace(R.id.fragment_container, frag1);
transaction.commit();
transaction.addToBackStack(null);
}
public void openFrag2(View view) {
transaction.replace(R.id.fragment_container, frag2);
transaction.commit();
transaction.addToBackStack(null);
}
}
My three fragment files are essentially identical with java files:
package com.example.connor.fragmenttestapp;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
#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);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
}
and .XML files:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.connor.fragmenttestapp.Fragment1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/frag1_text"
android:id="#+id/textView" />
</FrameLayout>
The logcat file for this error shows :
02-01 21:01:51.608 15413-15413/com.example.connor.fragmenttestapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.connor.fragmenttestapp, PID: 15413
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException: commit already called
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:630)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:603)
at com.example.connor.fragmenttestapp.MainActivity.openFrag2(MainActivity.java:37)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
What is causing this error and how can I fix the code to avoid it?
You need to begin a transaction each time instead of creating only one.
You can have a single FragmentManager, but must beginTransition every time.
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = = getSupportFragmentManager();
if (savedInstanceState == null) {
fm.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
fm.beginTransition().replace(R.id.fragment_container, frag1)
.addToBackStack(null).commit();
}
public void openFrag2(View view) {
fm.beginTransition().replace(R.id.fragment_container, frag2);
.addToBackStack(null).commit();
}
}
You can use this two functions
public void openNoHistoryFragment(Fragment fragment) {
FragmentTransaction ft = getActivity().getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.container,
fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commitAllowingStateLoss();
}
public void openFragment(Fragment fragment) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
// transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
create this each time when your want to make transaction.
transaction = getSupportFragmentManager().beginTransaction();
Related
can somebody help me please to show a .swf file into a WebView, I tried to do, but it shows a white windows instead of WebView. Also I tried to show a simple website and it shows also a empty window.
Fragment.java
package com.app.clupascu.oavm;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class FirstFragment extends Fragment {
#SuppressLint("SetJavaScriptEnabled")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
String url ="file:///android_asset/map.swf";
WebView mWebView=(WebView) v.findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mWebView.loadUrl(url);
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
Here I tried to load the .swf file into WebView.
I thought that the problem is in this file and I tried to load a simple website, but also without result.
Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
MainPage.java
package com.app.clupascu.oavm;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainPage extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
setTitle("Map");
FirstFragment fragment = new FirstFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fram, fragment);
fragmentTransaction.commit();
return true;
case R.id.navigation_dashboard:
setTitle("History");
SecondFragment fragment2 = new SecondFragment();
FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.fram, fragment2);
fragmentTransaction2.commit();
return true;
case R.id.navigation_notifications:
setTitle("Schedule");
ThirdFragment fragment3 = new ThirdFragment();
FragmentTransaction fragmentTransaction3 = getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.fram, fragment3);
fragmentTransaction3.commit();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
setTitle("Map");
FirstFragment fragment = new FirstFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fram, fragment);
fragmentTransaction.commit();
}
}
Thank you!
SWF is a ShockWaveFlash file. Web browsers can not run/display a ShockWave Flash File without the help of the Flash Plugin.
The Flash Plugin for Android has been discontinued several years ago. Therefore you won't succeed in making it run in a WebView.
Hence you have to re-think your application design and how you can achieve whyt you want without that SWF file.
Anyway it is not a good idea to start a new app using a technology the will reach its end of life in 2 years (end of 2020).
I use Android Tab Example with two tabs, view pager and fragments (structure on the image):
For get fragments i use the solution from this post.
When my device is rotation i want to display two fragments at the same time.
I the stackoverflow.com/questions/17970021 a similar problem, but I don't know how to apply the solution to my task, because i have TabLayout.
If you know idea, can you help me?
In activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
>
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
</FrameLayout>
In MainActivity.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.annotation.NonNull;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replaceFragment(0);
}
public void replaceFragment(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new TabOneFragment();
break;
case 1:
fragment = new TabTwoFragment();
break;
default:
break;
}
if (null != fragment) {
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
in TabOneFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabOneFragment extends Fragment {
private View inflatedView = null;
public TabOneFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_one, container, false);
return this.inflatedView;
}
}
in TabTwoFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabTwoFragment extends Fragment {
private View inflatedView = null;
public TabTwoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_two, container, false);
return this.inflatedView;
}
}
I am trying to call a fragment that acts as a side bar menu but when I try to run my app it says application has stopped. I have been trying all the ways I found on the internet. This is what I made so far.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.user.sample.MainActivity">
<TextView
android:onClick="menuHeader"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="☰"
android:layout_alignParentTop="true"
android:background="#931d21"
android:gravity="center_vertical"
android:paddingLeft="10dp" />
<fragment
android:name="com.example.user.sample.MenuFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment_container" />
</LinearLayout
MainActivity.java
package com.example.user.sample;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
public class MainActivity extends FragmentActivity {
private MenuFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void menuHeader(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment = new MenuFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
MenuFragment.java
package com.example.user.sample;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {#link OnListFragmentInteractionListener}
* interface.
*/
public class MenuFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public MenuFragment() {
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static MenuFragment newInstance(int columnCount) {
MenuFragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
// void onListFragmentInteraction(DummyItem item);
}
}
LOGCAT
02-10 10:11:19.236 3643-3643/com.example.user.sample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.sample, PID: 3643
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.sample/com.example.user.sample.MainActivity}: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3190)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450)
at android.app.Activity.setContentView(Activity.java:2366)
at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.RuntimeException: com.example.user.sample.MainActivity#197f8eef must implement OnListFragmentInteractionListener
at com.example.user.sample.MenuFragment.onAttach(MenuFragment.java:75)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1231)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1472)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1691)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3413)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450)
at android.app.Activity.setContentView(Activity.java:2366)
at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
The fragment will show when the ☰ is clicked. But the app crashes because of the existence of fragment inside the acitvity layout.
I already have a layout for the fragment and I didn't make any changes to it so I don't know if I need to post it here. Thanks
Your error is this
.RuntimeException: com.example.user.sample.MainActivity#197f8eef must implement OnListFragmentInteractionListener
So your activity needs to implement OnListFragmentInteractionListener.
So add
public class MainActivity extends FragmentActivity implements
OnListFragmentInteractionListener{
....
I want to show/hide fragment when i click the action bar menu item. But my app give me error when i click. Fragment coming on first run. When I want to hide fragment App give null error.
How can i solve this problem ?
Thanks in now.
Logcat
01-26 03:48:40.942 2295-2295/test.sy.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.BackStackRecord.run(BackStackRecord.java:661)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
LayerList.Java
package test.sy.myapplication;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LayerList extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.layerlist,container,false);
return mView;
}
}
MainActivity.Java
package test.sy.myapplication;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.showsth:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
ft.show(fm.findFragmentById(R.id.fragment));
ft.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
ft.show(fm.findFragmentById(R.id.fragment));
this line causes the problem
fm.findFragmentById(R.id.fragment) returns null.
With this line you are trying to find a fragment in layout/activity_main which is previously added to R.id.fragment.
If you didn't add or replace fragment before, it is obvious to return null AMK
I fix this issue.
This situation caused by adding fragment without any framelayout.
Once add framelayout to main activity. And give it id;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
android:layout_width="200dp"
android:layout_height="450dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:id="#+id/frameLayout"></FrameLayout>
Second;
Create fragment with its activty. In this example our fragment name may be FragmentTest.java and our Fragments activity may be fragment_activity.xml.
And adding fragment to main activiy;
In Oncreate method you should add this line;
FragmentTest Mfragmenttest = new FragmentTest();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//R.id.frameLayout is our frame layouts id.
ft.add(R.id.frameLayout, Mfragmenttest , "Hello Fragment");
ft.commit
I am trying to set up a fragment dynamically. I need to do it in the FragmentActivity. Here is what I have tried.
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment frag = new InputFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, frag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.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;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</RelativeLayout>
InputFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class InputFragment extends Fragment {
private Button submit;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.input, container,false);
submit = (Button)view.findViewById(R.id.input_submit_button);
submit.setOnClickListener(new SubmitButtonAction());
return view;
}
private class SubmitButtonAction implements OnClickListener
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment frag = new OutputFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, frag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
}
There is an compile error. Here it is.
Type mismatch: cannot convert from android.app.FragmentTransaction to android.support.v4.app.FragmentTransaction
This error is coming from FragmentTransaction ft = getFragmentManager().beginTransaction(); of MainActivity.java
I tried fixes suggested by Eclipse, but it gave me nothing. When I fix the error using exlipse suggestions, it gives another error. When I fix it using eclipse suggestions (clicking on eclipse suggestions) it comes back to the previous error.
What am I doing here wromg?
Try to use getSupportFragmentManager() instead of getFragmentManager()
If you want to use fragments below Android sdk vrsion 3.0,then use getSupportFragmentManager() method available in support 4 support lib.
(Make sure to put supportv4 lib in your lib folder and add in your project build path)
I'm not sure you can use transition with the support library. A few suggestions:
Remove this line ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
Or if you're targeting API 14 or higher you may instead extend Activity and use getFragmentManager()