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
Related
I'm building an app with Fragments and RecyclerView.
I am following this tutorial: THIS TUTORIAL
I'm using the tutorial's Building Message Fragment part to do this.
But I am receiving this error:
08-17 10:21:51.674 32646-32646/zca.zcaimobile E/AndroidRuntime: FATAL EXCEPTION: main
Process: zca.zcaimobile, PID: 32646
java.lang.RuntimeException: Unable to start activity ComponentInfo{zca.zcaimobile/zca.zcaimobile.activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at zca.zcaimobile.fragments.PaymentFragment.onViewCreated(PaymentFragment.java:43)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1127)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:604)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1244)
at android.app.Activity.performStart(Activity.java:6116)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
My PaymentFragment.java
package zca.zcaimobile.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import zca.zcaimobile.R;
import zca.zcaimobile.api.APIService;
import zca.zcaimobile.api.APIUrl;
import zca.zcaimobile.helper.PaymentAdapter;
import zca.zcaimobile.helper.SharedPrefManager;
import zca.zcaimobile.models.Payments;
public class PaymentFragment extends Fragment {
private RecyclerView recyclerViewMessages;
private RecyclerView.Adapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_messages, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Messages");
recyclerViewMessages = (RecyclerView) view.findViewById(R.id.recyclerViewMessages);
recyclerViewMessages.setHasFixedSize(true);
recyclerViewMessages.setLayoutManager(new LinearLayoutManager(getActivity()));
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIUrl.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<Payments> call = service.getPayments(SharedPrefManager.getInstance(getActivity()).getUser().getId());
call.enqueue(new Callback<Payments>() {
#Override
public void onResponse(Call<Payments> call, Response<Payments> response) {
adapter = new PaymentAdapter(response.body().getMessages(), getActivity());
recyclerViewMessages.setAdapter(adapter);
}
#Override
public void onFailure(Call<Payments> call, Throwable t) {
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
My fragment_payment.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.support.v7.widget.RecyclerView
android:id="#+id/recyclerViewMessages"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
I'm using the MessageFragment part of that tutorial as a reference for my PaymentFragment.java, because that part and my paymentfragment has the same function.
Can someone help me? I'm new to Android programming so I don't really know what's happening.
Thank you.
It's because your layout name fragment_payment.xml not the R.layout.fragment_messages. LayoutInflater can't find recyclerview in fragment_messages.xml
Change this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_payment, container, false);
}
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, "");
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 have just started writing my first piece of code in an android app, however when I run it with the following section uncommented it crashes (anything else I tell you would be a useless guess):
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
With the following error log:
04-07 17:45:30.897: E/AndroidRuntime(15210): FATAL EXCEPTION: main
04-07 17:45:30.897: E/AndroidRuntime(15210): Process: com.ollieapps.helloworld, PID: 15210
04-07 17:45:30.897: E/AndroidRuntime(15210): java.lang.IllegalStateException: Could not execute method of the activity
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3823)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View.performClick(View.java:4438)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$PerformClick.run(View.java:18422)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.handleCallback(Handler.java:733)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.reflect.InvocationTargetException
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3818)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 9 more
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.ollieapps.helloworld.MainActivity.onButton1Click(MainActivity.java:59)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 11 more
I'm sorry if I have included to much or too little, this is my first question, also I have already searched for 3 hours.
Full Code:
package com.ollieapps.helloworld;
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.CheckBox;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView; CheckBox pepBox, cheeseBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
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);
}
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
/**
* 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;
}
}
}
xml:
fragment:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ollieapps.helloworld.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pepperoni" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ExtraCheese" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButton1Click"
android:text="Show" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plain" />
</LinearLayout>
</RelativeLayout>
Main:
<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="com.ollieapps.helloworld.MainActivity"
tools:ignore="MergeRootFrame" />
It seems you built your views inside fragment_main.xml and not activity_main.xml.
When you first create a new android project, you have these files which are automatically created and opened:
Then, when you begin, you add views (e.g: a TextView) inside fragment_main.xml file. Finally, you tried to do a basically event with this view inside your Activity, something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Using layout activity_main.xml
// You try to set a simple text on the view (TextView) previously added
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("Simple Text"); // And you get an error here!
/*
* You do an fragment transaction to add PlaceholderFragment Fragment
* on screen - this below snippnet is automatically created.
*/
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
You cannot run your app or sometimes you have only a white screen, because the views that you tried to call/display are into the wrong layout..
Solution: Move all your stuff inside onCreateView method into the Fragment class.
As DoctororDrive said in his comment
Call views and do something in the related fragment and not the parent activity.
For example, in your case, these following lines:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
might be inside your fragment because you created it in fragment_main.xml layout. Then:
// start fragment
public static class PlaceholderFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Use the layout which is displayed it's fragment_main.xml
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Find your views here!
// Don't forget to findViewById attached to the inflated view "rootView.findView..."
pepBox = (CheckBox) rootView.findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) rootView.findViewById(R.id.checkBox2);
textView = (TextView) rootView.findViewById(R.id.textView1);
/*
* Do something here: click listener, set a text, check a box..
*/
return rootView;
}
/*
* Perform other methods still inside the fragment
*/
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
}
// end fragment
if (pepBox.isChecked()) {
This line of code is failing with a NullPointerException because pepBox was declared but it's not being initialized as it should (and is therefore null at this point in the code).
Here is its declaration line:
TextView textView; CheckBox pepBox, cheeseBox;
And here is its initialization:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
The problem is that (a) this line is not be called, or (b) findViewById(R.id.checkBox1) is returning null.
If findViewByID is returning null then you probably want to refer to this question, which addresses exactly this issue. Its "related questions", down the right-hand side, should also be helpful.
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