4

I'm trying to have a dialog where you can click a "next" button to swipe right to the next screen. I am doing that with a ViewPager and adapter:

  final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.voicedialog);
        dialog.setCanceledOnTouchOutside(false);

        MyPageAdapter adapter = new MyPageAdapter();
        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(adapter);

However, I get a NullPointerException saying that pager is null. Why is this happening? Here is the Page Adapter class:

public class MyPageAdapter extends PagerAdapter {
    public Object instantiateItem(ViewGroup collection, int position) {

        int resId = 0;
        switch (position) {
            case 0:
                resId = R.id.voice1;
                break;
            case 1:
                resId = R.id.voice2;
                break;
        }
        return collection.findViewById(resId);
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }
}

Here's my layout for the DIALOG:

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

Let me know on how to avoid this situation.

PS: Each of the layouts that should be in the view pager look like this, just diff. text:

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/voice2"
    xmlns:android="http://schemas.android.com/apk/res/android">

        <TextView
            android:text="Slide 1!"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView2"
            android:layout_gravity="center"
            android:textSize="50sp" />

    </RelativeLayout>
4
  • Post your layout xml Dec 26, 2016 at 3:42
  • @GurwinderSingh Done, I have edited the question Dec 26, 2016 at 3:46
  • You should call findViewById on dialog. Not on current activity. Dec 26, 2016 at 3:54
  • I think you are trying to bind your ViewPager before dialog created. You should bind it after dialog's onCreate() method.
    – kgnkbyl
    Jul 18, 2018 at 7:09

2 Answers 2

9

Without Using Enum Class

You should call findViewById on dialog. so for that you have to add dialog before findViewById..

Like this,

ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);

After solving your null pointer exception the other problem's solution here, if you wont use enum class you can use below code...

MainActivity.java

package demo.com.pager;

import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn= (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Dialog dialog = new Dialog(MainActivity.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.voicedialog);
                dialog.setCanceledOnTouchOutside(false);

                MyPageAdapter adapter = new MyPageAdapter(MainActivity.this);
                ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
                pager.setAdapter(adapter);
                dialog.show();
            }
        });


    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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="demo.com.pager.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

MyPageAdapter.java

package demo.com.pager;

import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by rucha on 26/12/16.
 */

public class MyPageAdapter extends PagerAdapter {

    Context mContext;
    int resId = 0;

    public MyPageAdapter(Context context) {
        mContext = context;
    }


    public Object instantiateItem(ViewGroup collection, int position) {

      /*  int resId = 0;
        switch (position) {
            case 0:
                resId = R.id.voice1;
                break;
            case 1:
                resId = R.id.voice2;
                break;
        }

        return collection.findViewById(resId);*/

        LayoutInflater inflater = LayoutInflater.from(mContext);
        switch (position) {
            case 0:
                resId = R.layout.fragment_blue;
                break;
            case 1:
                resId = R.layout.fragment_pink;
                break;
        }
        ViewGroup layout = (ViewGroup) inflater.inflate(resId, collection, false);
        collection.addView(layout);
        return layout;
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }
}

FragmentBlue.java

package demo.com.pager;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;

public class FragmentBlue extends Fragment  {

    private static final String TAG = FragmentBlue.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_blue, container, false);
        return view;
    }


}

fragment_blue.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4ECDC4">

</RelativeLayout>

voicedialog.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Please check and reply.

6
  • Okay, I did that, but now the dialog is just an empty screen with no contents or swiping...None of the layouts (voice1 or voice2) are even showing. Dec 26, 2016 at 5:27
  • Where did you inflate your layout ?
    – Piyush
    Dec 26, 2016 at 5:37
  • @RuchirBaronia i updated the answer check the answer and modify according to your code if any doubt ask again and if you like my ans plz upvoted and accept. Thank you. Dec 26, 2016 at 5:50
  • @RuchaBhatt Instead of posting another answer . you must be edited your first answer ! Otherwise moderator or other users will be downvoted to your answer !
    – Piyush
    Dec 26, 2016 at 5:52
  • I had to replace MyPageAdapter(MainActivity.this); by MyPageAdapter(getSupportFragmentManager());
    – Zach
    Aug 14, 2019 at 8:30
0

Using Enum Class

Try this code, This is working if any doubt ask again. Happy to help.

MainActivity.java

package demo.com.dialogdemo;

import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setupUIComponents();
        setupListeners();
    }

    private void setupUIComponents() {
        button = (Button) findViewById(R.id.button);
    }

    private void setupListeners() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Dialog dialogItemDetails = new Dialog(MainActivity.this);
                dialogItemDetails.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialogItemDetails.setContentView(R.layout.dialoglayout);
                dialogItemDetails.getWindow().setBackgroundDrawable(
                        new ColorDrawable(Color.TRANSPARENT));

                ViewPager viewPager = (ViewPager) dialogItemDetails.findViewById(R.id.viewPagerItemImages);
                viewPager.setAdapter(new CustomPagerAdapter(MainActivity.this));
                dialogItemDetails.show();

            }
        });
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dialog" />

</RelativeLayout>

ModelObject1.java

public enum ModelObject1 {

    RED(R.string.red, R.layout.fragment_one),
    BLUE(R.string.blue, R.layout.fragment_two);

    private int mTitleResId;
    private int mLayoutResId;

    ModelObject1(int titleResId, int layoutResId) {
        mTitleResId = titleResId;
        mLayoutResId = layoutResId;
    }

    public int getTitleResId() {
        return mTitleResId;
    }

    public int getLayoutResId() {
        return mLayoutResId;
    }

}

CustomPagerAdapter.java

package demo.com.dialogdemo;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by rucha on 26/12/16.
 */

public class CustomPagerAdapter  extends PagerAdapter {

    private Context mContext;

    public CustomPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        ModelObject1 modelObject = ModelObject1.values()[position];
        LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
        collection.addView(layout);
        return layout;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getCount() {
        return ModelObject1.values().length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        ModelObject1 customPagerEnum = ModelObject1.values()[position];
        return mContext.getString(customPagerEnum.getTitleResId());
    }

}

dailoglayout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txtHeaderTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="ITEM IMAGES"
        android:textStyle="bold" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPagerItemImages"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white" />

</RelativeLayout>

fragmentone.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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="one"/>

</LinearLayout>
4
  • @RuchirBaronia What problem did u face with this code ?
    – Piyush
    Dec 26, 2016 at 6:19
  • @Piyush Rather than the code being troublesome, I wanted to find a way to fix my own instead of just copying another. I also think using Enum is not necessary. Besides for the use of Enum, this is almost the exact same as what I provided in my question. I am just trying to figure out how to reference my layout in instantiateItem in MyPageAdapter since I think my problem is that I am not calling collection.addView(layout);, but I don't know how to get that layout object. Do you or @Rucha know? Dec 26, 2016 at 6:22
  • @RuchirBaronia enum is not necessary at all , i told you update your question and show us what you did till now.. and ok i get it you want to inflate layout without using enum is that your question? Dec 26, 2016 at 6:26
  • Then its as simple as you can check this @RuchirBaronia
    – Piyush
    Dec 26, 2016 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.