-3

Fragment whose layout contains button1

package com.example.shrey.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A simple {@link Fragment} subclass.
 */
public class PageFragment extends android.support.v4.app.Fragment {

    public PageFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.page_fragment_layout,container,false);

//      button initialisation
        Button button_a;
        button_a = view.findViewById(R.id.button1);
        button_a.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(PageFragment.this,
                        ScrollingActivity1.class);
                startActivity(myIntent);
            }
        });

        return view;
    }

}

On debugging I am getting the error:

"java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference"

I am providing my MainActivity code. Edit - adding zip file of my program. note- button1 is a button on one of the pages in viewpager of activity_main.xml. I have made an activity which I want to display on clicking button1

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/Constraint1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"
    tools:context="com.example.shrey.myapplication.MainActivity">

    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <!--code for action bar-->
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimaryDark"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

        <!--swipe view creating code-->
        <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="16dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </LinearLayout>
        <!--code for navigation drawer-->
        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/drawer_view" />
    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>

MainActivity

package com.example.shrey.myapplication;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import static javax.xml.datatype.DatatypeFactory.newInstance;

public class MainActivity  extends AppCompatActivity {
    private DrawerLayout drawerlayout;
    ViewPager viewpager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerlayout = findViewById(R.id.drawer_layout);

        viewpager = findViewById(R.id.view_pager);
        SwipeAdapter swipeadapter = new SwipeAdapter(getSupportFragmentManager());
        viewpager.setAdapter(swipeadapter);

//        set status bar color code
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(this.getResources().getColor(R.color.material_blue_grey_950));
        }

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionbar = getSupportActionBar();
        actionbar.setDisplayHomeAsUpEnabled(true);
        actionbar.setHomeAsUpIndicator(R.drawable.ic_navdrawer);
//        <!-- code to change title and its color. -->
        actionbar.setTitle(Html.fromHtml("<font color='#ffffff'>Skill India App </font>"));

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                        // set item as selected to persist highlight
                        menuItem.setChecked(true);
                        // close drawer when item is tapped
                        drawerlayout.closeDrawers();

                        // Add code here to update the UI based on the item selected
                        // For example, swap UI fragments here

                        return true;
                    }
                });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                drawerlayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DarkShadow
  • 197
  • 2
  • 13

2 Answers2

1

I only see one setOnClickListener, so the problem with the code is here:

//      button initialisation
        Button button_a;
        button_a = findViewById(R.id.button1);
        button_a.setOnClickListener(new View.OnClickListener() {

You are creating a Button called button_a (initially null), and then binding it with findViewById. The problem is that the findViewById is not finding anything with the id "button1" in your content view, in this case R.layout.activity_main. So when the next line is run, button_a is still null and you are doing null.setOnClickListener, which isn't allowed.

Need more information to fully answer, as Bhuvanesh BS mentioned, posted your activity_main.xml.

Mark
  • 139
  • 1
  • 8
  • i have provided the activity_main.xml and explained where is button1 can you explain the error now – DarkShadow Mar 18 '18 at 07:53
  • I don't see the button1 in your activity_main, it is part of a different view? You would need to run something like: `button_a = someOtherView.findViewById(R.id.button1);` It looks like your ViewPager might end up holding fragments? If it is holding separate views, and the button is on one of those views, it should be that view that handles the onClick. For example, if your ViewPager has some fragments and one of the fragments has button1, that fragment should do the onClick, not the Activity. – Mark Mar 18 '18 at 07:59
  • you mean i have to apply the listener in the fragment whose layout xml has the button1? – DarkShadow Mar 18 '18 at 08:02
  • Yeah, your fragment should know about the button, so it can do the onClick. – Mark Mar 18 '18 at 08:03
  • it is showing an error in the intent line. " cannot resolve Constructor " i am adding the fragment whose layout contains button1 – DarkShadow Mar 18 '18 at 08:10
1

First of all, You cannot call fragment class in intent. Fragment is the part of your activity that it contains. Put there your activity name.

Button button_a;
        button_a = view.findViewById(R.id.button1);
        button_a.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(MainActivity.this,
                        ScrollingActivity1.class);
                startActivity(myIntent);
            }
        });

Then, I cannot see where you add your fragment to viewpager in your code. You need to add an instance of your fragment to your pager to see the actual layout you created, I assume it is in SwipeAdapter

And finally, get rid of the button1 onCLickListener in the MainActivity class.

And it will work

Rainmaker
  • 10,294
  • 9
  • 54
  • 89
  • It was showing the error when I tried your code. On an answer above someone told me I have to place the listener on the page which contains the button and PageFragment contains the button. Let me explain the whole situation, I created a button in Pagefragment and created several fragments and made a swipeview from them, then i placed a button in one fragment and i want the button to open an activity i created when clicked. Now can you please explain. – DarkShadow Mar 18 '18 at 08:40
  • This someone is right, you put this code in fragment as i see you did, but you put in the intent the name of the fragment which is wrong . You need to use the name of the activity that contains this fragment but place the intent in the fragment (where it is now) And then get rid of the listener in your activity. I hope it makes sense. – Rainmaker Mar 18 '18 at 08:53
  • or which is more easier,put Intent intent = new Intent (getActivity(), ScrollingActivity1.class); instead of Intent myIntent = new Intent(PageFragment.this, ScrollingActivity1.class); – Rainmaker Mar 18 '18 at 08:55
  • It worked Thank you very much. But can you explain why getActivity() worked and not the previous one for Future reference – DarkShadow Mar 18 '18 at 08:59
  • Because getActivity() calls for the reference to the specific activity you put your fragment in. A class can have difference instances. And this method gets the path to the one your fragment connected to – Rainmaker Mar 18 '18 at 09:05
  • thanks a lot. can I find somehow which activity is the fragment connected to – DarkShadow Mar 18 '18 at 09:26
  • by using this method getActivity(); you can assign it to some instance and reuse it throughout the fragment's code. You put MainActivity mActivity = (MainActivity) getActivity(); And now mActivity is your instance of activity in fragment – Rainmaker Mar 18 '18 at 09:38