I have an activity holding a fragment, in this fragment there is a button , when it is clicked, a dialog is popped out.
In this dialog, there is a Viewpager, which holds some fragments to display.
Here are the code and the error, please spare your valuable time to show me where I am wrong. I much appreciate your help.
MainActivity.class
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
}
}
MyFragment.class
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sandbox, container, false);
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
PagerDialog dialog = new PagerDialog(getActivity(),
getChildFragmentManager());
dialog.show();
}
});
return v;
}
}
PagerDialog.class
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class PagerDialog extends Dialog {
ViewPager mViewPager;
FragmentStatePagerAdapter mAdapter;
FragmentManager mFragmentManager;
public PagerDialog(Context context, FragmentManager fm) {
super(context);
mFragmentManager = fm;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
mViewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyAdapter(mFragmentManager);
mViewPager.setAdapter(mAdapter);
}
private class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return new DummyFragment();
}
#Override
public int getCount() {
return 2;
}
}
private class DummyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dummy_layout,
container, false);
return v;
}
}
}
Here is the dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Here is the error
03-06 19:43:38.487: E/AndroidRuntime(1167): FATAL EXCEPTION: main
03-06 19:43:38.487: E/AndroidRuntime(1167): Process: com.me.sandbox, PID: 1167
03-06 19:43:38.487: E/AndroidRuntime(1167): java.lang.IllegalArgumentException: No view found for id 0x7f05003d (com.mochimira.sandbox:id/pager) for fragment DummyFragment{b2d9f8c8 #0 id=0x7f05003d}
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:939)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-06 19:43:38.487: E/AndroidRuntime(1167): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer.doFrame(Choreographer.java:544)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.os.Handler.handleCallback(Handler.java:733)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.os.Handler.dispatchMessage(Handler.java:95)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.os.Looper.loop(Looper.java:136)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-06 19:43:38.487: E/AndroidRuntime(1167): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 19:43:38.487: E/AndroidRuntime(1167): at java.lang.reflect.Method.invoke(Method.java:515)
03-06 19:43:38.487: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-06 19:43:38.487: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-06 19:43:38.487: E/AndroidRuntime(1167): at dalvik.system.NativeStart.main(Native Method
I have found a solution to the problem and have modified your classes so that this error no longer occurs.
The only major difference was that you should use a DialogFragment instead of a Dialog, that way you have access to call getChildFragmentManager() and receive the correct FragmentManager from the DialogFragment.
Even though you were using getChildFragmentManager() before, it was coming from MyFragment and the PagerDialog class was not a child fragment in MyFragment.
I have tested the code below, and it should be working fine now.
MyFragment
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sandbox, container, false);
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
DialogFragment newFragment = PagerDialog.newInstance();
newFragment.show(getChildFragmentManager(), "dialog");
}
});
return v;
}
}
PagerDialog
public class PagerDialog extends DialogFragment {
public static PagerDialog newInstance() {
return new PagerDialog();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_fragment, container, false);
ViewPager mViewPager = (ViewPager) v.findViewById(R.id.view_pager);
/* Use childFragmentManager here provided from the PagerDialog */
MyAdapter mAdapter = new MyAdapter(getChildFragmentManager());
mViewPager.setAdapter(mAdapter);
return v;
}
private class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return new DummyFragment();
}
#Override
public int getCount() {
return 2;
}
}
}
DummyFragment
public class DummyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dummy_layout, container, false);
return v;
}
}
fragment_sandbox.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test Fragment Dialog Pager"
android:textSize="24sp"
android:padding="20dp" />
</LinearLayout>
dialog_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment Dialog Title Text "
android:padding="10dp"
android:textColor="#333"
android:textSize="24sp"/>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</LinearLayout>
fragment_dummy_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment Dummy Text"
android:textSize="24sp"
android:textColor="#ff0000"/>
</LinearLayout>
I found in Google a blog post, it says that viewpager doesn't work on Dialog.
It also says we should use DialogFragment instead.
Here is the link to that blog: http://www.intellicode.in/viewpager-inside-dialog/
getChildFragmentManager() is available since API 17 while you're using the v4 support library. Try using the support fragment manager instead:
PagerDialog dialog = new PagerDialog(getActivity(),
getActivity().getSupportFragmentManager());
The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog directly. Instead, use one of the following subclasses:
AlertDialogA dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. And also DatePickerDialog or TimePickerDialog.
These classes define the style and structure for your dialog, but you should use a DialogFragment as a container for your dialog. The DialogFragment class provides all the controls you need to create your dialog and manage its appearance, instead of calling methods on the Dialog object.
For more detail please go through Dialog Design
The error sounds like it's looking for the id pager in the xml file for DummyFragment (fragment_dummy_layout.xml). I wonder if this is due to calling View v = inflater.inflate(R.layout.fragment_dummy_layout, container, false); in the same file as setContentView(R.layout.dialog);. Have you tried separating DummyFragment into it's own file?
You could also try
View v = getActivity().getLayoutInflater().inflate(R.layout.fragment_dummy_layout,
container, false);
Try using DialogFragment and pass getChildFragmentManager() to your FragmentPagerAdapter's constructor.
DialogFragment:
public static class MyDialogFragment extends DialogFragment {
private ViewPager viewPager;
MySectionPagerAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.m_layout, container);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
mAdapter = new MySectionPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
return view;
}
}
so far, we can't figure out why there is an error, but I have a way to work around this, using this tip:
Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the manifest element:
<activity android:theme="#android:style/Theme.Holo.Dialog"
Based on this tip, I don't make PagerDialog extend Dialog but from Fragment. And then put this Fragment inside an Activity , set the theme of this activity as above in AndroidManifest.xml.
The updated code for the PagerDialog is as followed.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PagerDialog extends Fragment {
ViewPager mViewPager;
FragmentStatePagerAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.id.dialog, container, false);
mViewPager = (ViewPager) v.findViewById(R.id.pager);
mAdapter = new MyAdapter(getFragmentManager());
mViewPager.setAdapter(mAdapter);
return v;
}
private class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return new DummyFragment();
}
#Override
public int getCount() {
return 2;
}
}
private class DummyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dummy_layout,
container, false);
return v;
}
}
}
If you have any better solutions or you can find out why the original code in my question does not work, please teach me. I am a newbie in Android programing and I am happy to learn from you all.
Cheers.
I think you used
Dialog dialog = new Dialog(context);
Instends this.
1st Step: Used DialogFragment
public class MyCustomDialog extends DialogFragment {
Button mButton;
EditText mEditText;
List<MasterPageModel> listdata;
int position;
ViewPager viewpager;
public MyCustomDialog(List<MasterPageModel> listdata, int position) {
this.listdata = listdata;
this.position = position;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View dialog = inflater.inflate(R.layout.dailoglayout, container);
final Dialog dailog = getDialog();
dailog.getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
dailog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dailog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ImageView closebtn = (ImageView) dialog.findViewById(R.id.closeimgeview);
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dailog.dismiss();
}
});
viewpager = (ViewPager) dialog.findViewById(R.id.dailog_viewpager);
**viewpager.setAdapter(new PagerAdapter(getChildFragmentManager(), listdata));** //This Line is Very important
viewpager.setCurrentItem(position);
return dialog;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen); //For Full Screen of DailogBox
}
}
2nd Step :set The FragmentViewPager
public class PagerAdapter extends FragmentPagerAdapter {
private final List<MasterPageModel> pages;
public PagerAdapter(FragmentManager fm, List<MasterPageModel> pages) {
super(fm);
this.pages = pages;
}
#Override
public Fragment getItem(int position) {
return new ViewPagerFragment(pages.get(position));
}
#Override
public int getCount() {
return pages.size();
}
}
3rd Step : Fragment View For ViewPager:
public class ViewPagerFragment extends Fragment {
MasterPageModel masteDetailModel;
public ViewPagerFragment(MasterPageModel questionItem) {
this.masteDetailModel = questionItem;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pagerlayout, container, false);
ImageView image = (ImageView) v.findViewById(R.id.pager_imageview);
Log.i("Image", "=>" + masteDetailModel.imagelarge);
Picasso.with(getActivity()).load(masteDetailModel.imagethumb).error(R.drawable.img).into(image);
return v;
}
4th How to Use this dialogfragment:
MyCustomDialog fragment1 = new MyCustomDialog(listdata, position);
EditionDetailActivity act = (EditionDetailActivity) context;
FragmentManager fm = act.getSupportFragmentManager();
fragment1.show(fm, "");
Related
I am trying to create an Image Slider containing 4 images for my application and i've been running into the following errors. I've tried searching and have found similiar titles but the problems are different.
This is the logcat:
example.prgguru.com.wallit E/AndroidRuntime: FATAL EXCEPTION: main
Process: example.prgguru.com.wallit, PID: 32048
java.lang.RuntimeException: Unable to start activity ComponentInfo{example.prgguru.com.wallit/example.prgguru.com.wallit.MainActivity}: android.view.InflateException: Binary XML file line #3: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #3: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:350)
at android.app.Activity.setContentView(Activity.java:2059)
at example.prgguru.com.wallit.MainActivity.onCreate(MainActivity.java:13)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class example.prgguru.com.wallit.MainActivityFragment that is not a Fragment
at android.app.Fragment.instantiate(Fragment.java:585)
at android.app.Fragment.instantiate(Fragment.java:561)
at android.app.Activity.onCreateView(Activity.java:5066)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:350)
at android.app.Activity.setContentView(Activity.java:2059)
at example.prgguru.com.wallit.MainActivity.onCreate(MainActivity.java:13)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException
at android.app.Fragment.instantiate(Fragment.java:585)
at android.app.Fragment.instantiate(Fragment.java:561)
at android.app.Activity.onCreateView(Activity.java:5066)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:350)
at android.app.Activity.setContentView(Activity.java:2059)
at example.prgguru.com.wallit.MainActivity.onCreate(MainActivity.java:13)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
This is my Main Activity.java:
package example.prgguru.com.wallit;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:name="example.prgguru.com.wallit.MainActivityFragment"
android:id="#+id/fragment"
tools:layout="#layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#32383d">
<!-- ViewPager -->
<!-- Footer -->
<android.support.v4.view.ViewPager
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageviewPager" />
<include layout="#layout/footer"/>
</FrameLayout>
MainActivityFragment.java
package example.prgguru.com.wallit;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivityFragment extends Fragment {
private ViewPager _mViewPager;
private ImageViewPagerAdapter _adapter;
private ImageView _btn1, _btn2, _btn3,_btn4;
public MainActivityFragment() {
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setUpView();
setTab();
onCircleButtonClick();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
private void onCircleButtonClick() {
_btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn1.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(0);
}
});
_btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn2.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(1);
}
});
_btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn3.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(2);
}
});
_btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn4.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(3);
}
});
}
private void setUpView() {
_mViewPager = (ViewPager) getView().findViewById(R.id.imageviewPager);
_adapter = new ImageViewPagerAdapter(getActivity(), getFragmentManager());
_mViewPager.setAdapter(_adapter);
_mViewPager.setCurrentItem(0);
initButton();
}
private void setTab() {
_mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
_btn1.setImageResource(R.drawable.holo_circle);
_btn2.setImageResource(R.drawable.holo_circle);
_btn3.setImageResource(R.drawable.holo_circle);
_btn4.setImageResource(R.drawable.holo_circle);
btnAction(position);
}
});
}
private void btnAction(int action) {
switch (action) {
case 0:
_btn1.setImageResource(R.drawable.fill_circle);
break;
case 1:
_btn2.setImageResource(R.drawable.fill_circle);
break;
case 2:
_btn3.setImageResource(R.drawable.fill_circle);
break;
case 3:
_btn4.setImageResource(R.drawable.fill_circle);
break;
}
}
private void initButton() {
_btn1 = (ImageView) getView().findViewById(R.id.btn1);
_btn1.setImageResource(R.drawable.fill_circle);
_btn2 = (ImageView) getView().findViewById(R.id.btn2);
_btn3 = (ImageView) getView().findViewById(R.id.btn3);
_btn4 = (ImageView) getView().findViewById(R.id.btn4);
}
private void setButton(Button btn, String text, int h, int w) {
btn.setWidth(w);
btn.setHeight(h);
btn.setText(text);
}
}
Your Activity extends from Activity and not AppCompatActivity. But your fragment extends from android.support.v4.app.Fragment. You must use one type of fragment: from support library or normal one.
Try to change extends Fragment from android.app.Fragment in your fragment class.
I have an app that simply displays 1 picture, implemented through Picasso. The onClick works fine if I replace the contents with a simple toast, so it must be the MediaPlayer calls. I don't know why it keeps crashing though.
package com.example.andrew.crossfade;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends ActionBarActivity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setClickable(true);
Picasso.with(this)
.load("http://i.imgur.com/vpeH7S2.jpg")
.into(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.later);
mp.start();
}
});
}
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;
}
}
}
The XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
And finally, the log cat:
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41f38da0)
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.andrew.crossfade, PID: 18409
java.lang.NullPointerException
at com.example.andrew.crossfade.MainActivity$1.onClick(MainActivity.java:47)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
something is null in your code
java.lang.NullPointerException
call mp.prepare() before start
and make sure R.raw.later is playable audio for media player
I got this error message state android.view.InflateException: Binary XML file line #9: Error inflating class fragment. Is it because of i'm not extending it into fragment in MessagesFragment? By the way, my app using TabHost.
FirstFragment.java
package com.xxxxx.yyyyy.match;
import com.xxxxx.yyyyy.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
public FirstFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = LayoutInflater.from(getActivity()).inflate(R.layout.first_fragment,
null);
return v;
}
}
first_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/darker_gray"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".FirstFragment" >
<fragment
android:name="com.xxxxx.yyyyy.chat.MessagesFragment"
android:id="#+id/msg_list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</RelativeLayout>
MessagesFragment.java
package com.xxxxx.yyyyy.chat;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.xxxxx.yyyyy.R;
import com.xxxxx.yyyyy.library.chat.DataProvider;
import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MessagesFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final DateFormat[] df = new DateFormat[] {
DateFormat.getDateInstance(), DateFormat.getTimeInstance()};
private OnFragmentInteractionListener mListener;
private SimpleCursorAdapter adapter;
private Date now;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
now = new Date();
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.chat_list_item,
null,
new String[]{DataProvider.COL_MSG, DataProvider.COL_AT},
new int[]{R.id.text1, R.id.text2},
0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
switch(view.getId()) {
case R.id.text1:
LinearLayout root = (LinearLayout) view.getParent().getParent();
if (cursor.getString(cursor.getColumnIndex(DataProvider.COL_FROM)) == null) {
root.setGravity(Gravity.RIGHT);
root.setPadding(50, 10, 10, 10);
} else {
root.setGravity(Gravity.LEFT);
root.setPadding(10, 10, 50, 10);
}
break;
case R.id.text2:
TextView tv = (TextView) view;
tv.setText(getDisplayTime(cursor.getString(columnIndex)));
return true;
}
return false;
}
});
setListAdapter(adapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setDivider(null);
Bundle args = new Bundle();
args.putString(DataProvider.COL_EMAIL, mListener.getProfileEmail());
getLoaderManager().initLoader(0, args, this);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public String getProfileEmail();
}
private String getDisplayTime(String datetime) {
try {
Date dt = sdf.parse(datetime);
if (now.getYear()==dt.getYear() && now.getMonth()==dt.getMonth() && now.getDate()==dt.getDate()) {
return df[1].format(dt);
}
return df[0].format(dt);
} catch (ParseException e) {
return datetime;
}
}
//----------------------------------------------------------------------------
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String profileEmail = args.getString(DataProvider.COL_EMAIL);
CursorLoader loader = new CursorLoader(getActivity(),
DataProvider.CONTENT_URI_MESSAGES,
null,
DataProvider.COL_FROM + " = ? or " + DataProvider.COL_TO + " = ?",
new String[]{profileEmail, profileEmail},
DataProvider.COL_AT + " DESC");
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
Output from logcat
03-06 16:52:05.729: E/AndroidRuntime(5419): FATAL EXCEPTION: main
03-06 16:52:05.729: E/AndroidRuntime(5419): android.view.InflateException: Binary XML file line #9: Error inflating class fragment
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
03-06 16:52:05.729: E/AndroidRuntime(5419): at com.xxxxx.yyyyy.FirstFragment.onCreateView(FirstFragment.java:38)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.os.Handler.handleCallback(Handler.java:730)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.os.Handler.dispatchMessage(Handler.java:92)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.os.Looper.loop(Looper.java:137)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.app.ActivityThread.main(ActivityThread.java:5136)
03-06 16:52:05.729: E/AndroidRuntime(5419): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 16:52:05.729: E/AndroidRuntime(5419): at java.lang.reflect.Method.invoke(Method.java:525)
03-06 16:52:05.729: E/AndroidRuntime(5419): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-06 16:52:05.729: E/AndroidRuntime(5419): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-06 16:52:05.729: E/AndroidRuntime(5419): at dalvik.system.NativeStart.main(Native Method)
03-06 16:52:05.729: E/AndroidRuntime(5419): Caused by: java.lang.ClassCastException: com.xxxxx.yyyyy.HomeActivity#419d4fa8 must implement OnFragmentInteractionListener
03-06 16:52:05.729: E/AndroidRuntime(5419): at com.xxxxx.yyyyy.chat.MessagesFragment.onAttach(MessagesFragment.java:49)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:848)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1039)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1141)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.app.Activity.onCreateView(Activity.java:4746)
03-06 16:52:05.729: E/AndroidRuntime(5419): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
03-06 16:52:05.729: E/AndroidRuntime(5419): ... 20 more
I see this lines in your layout code :
android:layout_height="0dip"
android:layout_weight="1"
RelativeLayout does not support weight attribute. Your MessageFragment's height will always be 0. So you should set layout_height to match_parent.
Also if possible, post stack trace of your error.
Also you have used Fragment from support library in FirstFragment but not in MessageFragment. It must be a typo which need to be fixed or it will give you an error on devices with API less than 11.
Edit : It seems your HomeActivity is not implementing OnFragmentInteractionListener, which is throwing ClassCastException in onAttach callback.
call your setListAdapter(adapter); in onActivityCreated()
check the lifecycle methodes
http://developer.android.com/guide/components/fragments.html
onCreate() calls before initializing the fragment;
also chenge this
View v = LayoutInflater.from(getActivity()).inflate(R.layout.first_fragment,
false);
In your MessagesFragment's onAttach, your com.xxxxx.yyyyy.HomeActivity is passed in as activity.
Then, in the following code, you expect HomeActivity is also OnFragmentInteractionListener
mListener = (OnFragmentInteractionListener) activity;
To solve this, you need to make your HomeActivity
public class HomeActivity extends Activity implements OnFragmentInteractionListener
Not sure if this will fix the problem, but I had one similar to it and I couldn't believe how easy it was to miss it / fix.
If you check your xml file, you will see your fragment labeled as:
<fragment
android:name="com.xxxxx.yyyyy.chat.MessagesFragment"
android:id="#+id/msg_list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
Try simply capitalizing the 'f' in 'Fragment' so that the XML Auto complete will recognize that you likely mean a (android.support.v4.app.Fragment)
I am currently trying to get the basic My First App tutorial of Android (created by google) to work, but I'm having some issues. Currently how the app is made no errors show up in Eclipse, but when I run the app and click the Send button, the app crashes displaying Unfortunately, My First App has stopped.
Looking in the Log cat for the error it states that
java.lang.IllegalStateException: Could not find a method sendMessage(View)
in the activity class com.example.myfirstapp.MainActivity for onClick handler
on view class android.widget.Button.
sendMessage does exist in the MainActivity class, but it is a nested class inside a function PlaceholderFragment. Originally I thought that this was an indexing error so I tried calling sendMessage like a nested class android:onClick="PlaceholderFragment.sendMessage" with no success. I have included the fragment_main and MainActivity class as well as my full logcat error. Thanks for any help.
MainActivity:
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#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();
}
}
#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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
}
Fragment Main:
<?xml version="1.0" encoding="utf-8"?>
<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="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
LogCat:
04-25 12:04:07.220: D/(1274): HostConnection::get() New Host Connection established 0xb8e4f238, tid 1274
04-25 12:04:07.330: W/EGL_emulation(1274): eglSurfaceAttrib not implemented
04-25 12:04:07.340: D/OpenGLRenderer(1274): Enabling debug mode 0
04-25 12:04:10.620: D/AndroidRuntime(1274): Shutting down VM
04-25 12:04:10.620: W/dalvikvm(1274): threadid=1: thread exiting with uncaught exception (group=0xb2a6bba8)
04-25 12:04:10.750: E/AndroidRuntime(1274): FATAL EXCEPTION: main
04-25 12:04:10.750: E/AndroidRuntime(1274): Process: com.example.myfirstapp, PID: 1274
04-25 12:04:10.750: E/AndroidRuntime(1274): java.lang.IllegalStateException: Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.MainActivity for onClick handler on view class android.widget.Button
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$1.onClick(View.java:3810)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View.performClick(View.java:4438)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$PerformClick.run(View.java:18422)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Looper.loop(Looper.java:136)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:04:10.750: E/AndroidRuntime(1274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-25 12:04:10.750: E/AndroidRuntime(1274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-25 12:04:10.750: E/AndroidRuntime(1274): at dalvik.system.NativeStart.main(Native Method)
04-25 12:04:10.750: E/AndroidRuntime(1274): Caused by: java.lang.NoSuchMethodException: sendMessage [class android.view.View]
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.Class.getConstructorOrMethod(Class.java:472)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.Class.getMethod(Class.java:857)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$1.onClick(View.java:3803)
04-25 12:04:10.750: E/AndroidRuntime(1274): ... 11 more
04-25 12:04:12.720: I/Process(1274): Sending signal. PID: 1274 SIG: 9
It looks like your problem is that the sendMessage function should be included in your MainActivity instead of nested in your fragment.
The debug line:
java.lang.IllegalStateException: Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.MainActivity for onClick handler on view class android.widget.Button
shows that the application is looking in your MainActivity class for this method.
place sendMessage(View view) method inside MainActivity class instead of PlaceholderFragment class
Handling clicklistener from xml is not always a good idea. Set a clicklistener in the fragment for the button and call sendMessage method from onClick method of clicklistener.
First set a ID for your button (Example : sendButton).
Then,
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);
Button b = (Button) rootView.findViewByID(R.id.sendButton);
//Here set the clickListener and call sendMessage method
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Or implement View.OnClickListener in the fragment then have a case statement like:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sendButton:
sendMessage();
break;
default:
Log.i(TAG, "Unknown: " + view.getId());
break;
}
}
Do it programmatically:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.my_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// handle click here
}
});
return rootView;
}
and insert this into Button section in your main activity layout:
android:id="#+id/my_button"
android:onClick="sendMessage"
button onClick attribute search the corresponding method in the Activity. but you define that method in the Fragment that's why you get the exception
method could not find exception.
Android Recommended way to do handle the onClick for button inside the fragment is
First Assign id to Button
<?xml version="1.0" encoding="utf-8"?>
<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="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
/>
</LinearLayout>
your Fragment then register the button with onClick listener
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements OnItemClickListener{
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(this);
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
public void onClick(View view)
{
sendMessage(view);
}
}
I am trying to implement pageviewer in my app using this tutorial. But my app force closes. It shows android.view.InflateException: Binary XML file line #2: Error inflating class com.example.viewpager.ScrollView. Where I am going wrong? I am a beginner in android so please guide me. I thought I might have imported wrong libs as my app is supporting API 10. So I searched other answers but of no use. Here is my code:
MainActvity.java
package com.example.viewpager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSlidePagerFragment.java
package com.example.viewpager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
actvity_main.xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_slide_screen_page.xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.viewpager.ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Page 1" />
</com.example.viewpager.ScrollView>
Log cat:
android.view.InflateException: Binary XML file line #2: Error inflating class com.example.viewpager.ScrollView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581)
at android.view.LayoutInflater.inflate(LayoutInflater.java:386)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at com.example.viewpager.ScreenSlidePageFragment.onCreateView(ScreenSlidePageFragment.java:14)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
at android.view.View.measure(View.java:8313)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
at android.view.View.measure(View.java:8313)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
at android.view.View.measure(View.java:8313)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
at android.view.View.measure(View.java:8313)
at android.view.ViewRoot.performTraversals(ViewRoot.java:845)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.example.viewpager.ScrollView in loader dalvik.system.PathClassLoader[/data/app/com.example.viewpager-2.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.view.LayoutInflater.createView(LayoutInflater.java:471)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
... 33 more
change adapter to:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
int layouts[];
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
layouts=new int[]{R.layout.fragment_slide_screen_page1,R.layout.fragment_slide_screen_page2,R.layout.fragment_slide_screen_page3,R.layout.fragment_slide_screen_page4,R.layout.fragment_slide_screen_page5};
}
#Override
public Fragment getItem(int position) {
ScreenSlidePageFragment fragment=new ScreenSlidePageFragment();
fragment.setContent(layouts[position]);
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
and in fragment:
public class ScreenSlidePageFragment extends Fragment {
int layout;
public void setContent(int layout){
this.layout=layout;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(layout, container, false);
return rootView;
}
}
Although not sure what change you want in each fragment but the above will require you to create 5 layout xmls that you can set every time you create a new Fragment.
Even I encountered crash.
This is because I was calling mAdapter.notifyDataSetChanged(); inside
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
Later I shifted the method to
#Override
public void onPageSelected(int arg0) {
mAdapter.notifyDataSetChanged();
}
So that did the trick