首页 > 解决方案 > 一旦登录成功,Android 初始登录屏幕然后使用片段在屏幕之间滑动

问题描述

我正在尝试创建一个 Android 应用程序,然后有一个初始登录屏幕来检测用户是管理员还是用户。登录后,用户(取决于他们的角色)将看到不同的选项卡在不同的选项卡之间滑动。我有一个基本的应用程序,它以登录活动和登录来解密用户角色(目前使用静态值)。第一部分没问题。现在,当我在登录屏幕后尝试使用 Fragments 时,我被卡住了。

I have a LoginActivity that has an onClikcListener on a button after user enters credentials. Depending on whether the user is Amin or General Users, it will just to a new activity either activity_vote_admin or activity_vote_user. At this point I am stuck. Any ideas if what I am trying to do is valid. Or is there a better way to do this. At the moment I am getting this error.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.confidencevotefragmentrebuild/com.example.confidencevotefragmentrebuild.activity_vote_admin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.

LoginActivity (this is my main activity)
...
package com.example.confidencevotefragmentrebuild;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {

    private static EditText username;
    private static EditText password;
    public static TextView attempts;
    private static Button submit_button;
    int attempt_counter = 5;

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

    }

    public void loginButton() {
        username = (EditText) findViewById(R.id.editText);
        password = (EditText) findViewById(R.id.editText2);
        attempts = (TextView) findViewById(R.id.textView_Attempts);


        //Reference button view
        final Button submit_button = findViewById(R.id.submit_button);
        // perform click event on button
        submit_button.setOnClickListener(new View.OnClickListener() {
                                             @Override
                                             public void onClick(View v) {

                                                 if (username.getText().toString().equals("admin") &&
                                                         password.getText().toString().equals("pass")) {
                                                     Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
                                                             Toast.LENGTH_SHORT).show();
                                                     Intent intent = new Intent(LoginActivity.this, activity_vote_admin.class);
                                                     startActivity(intent);
                                                 } else if (username.getText().toString().equals("user") &&
                                                         password.getText().toString().equals("pass")) {
                                                     Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
                                                             Toast.LENGTH_SHORT).show();
                                                     Intent intentUser = new Intent(LoginActivity.this, activity_vote_user.class);
                                                     startActivity(intentUser);

                                                 } else {
                                                     Toast.makeText(LoginActivity.this, "User or Password incorrect",
                                                             Toast.LENGTH_SHORT).show();
                                                     attempt_counter--;
                                                     attempts.setText(Integer.toString(attempt_counter));
                                                     if (attempt_counter == 0) {

                                                         Toast.makeText(LoginActivity.this, "Too many failed attempts, please close app and try again",
                                                                 Toast.LENGTH_SHORT).show();
                                                         submit_button.setEnabled(false);
                                                     }

                                                 }
                                             }
                                         }
        );
    }
}

...

Activity_vote_admin

...

package com.example.confidencevotefragmentrebuild;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

public class activity_vote_admin extends AppCompatActivity {

    /**
     * Field for selecting the number of confidence votes
     */
    RatingBar mResults;
    private RatingBar rBar;
    Button mBtn;

    /**
     * Spinner field to enter the project name
     */
    private Spinner mProjectSpinner;

    /**
     * Projects. The possible values are:
     * stored locally - Needs to get values from a database. TODO
     */
    int mProject = 0;

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

            // Find the view pager that will allow the user to swipe between fragments
            ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

            // Create an adapter that knows which fragment should be shown on each page
            AdminFragmentPagerAdapter adapter = new AdminFragmentPagerAdapter(getSupportFragmentManager());

            // Set the adapter onto the view pager
            viewPager.setAdapter(adapter);

            // initiate a rating bar
            rBar = findViewById(R.id.rating_bar);
            //float vote = rBar.getRating();

            // Find all relevant views for user input
            mResults = findViewById(R.id.rating_bar);

            mProjectSpinner = findViewById(R.id.spinner_project);

            // Run getRating method to get rating number from a rating bar
            //getRating();

            // Initiate button
            mBtn = findViewById(R.id.voteButton);

            // perform click event on button
            mBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // get values and then displayed in a toast
                    //String totalStars = "Total Stars:: " + RatingBar.getNumStars();
                    float vote = rBar.getRating();
                    String rating = "Rating : " + vote;
                    Toast.makeText(getApplicationContext(), rating + "\n", Toast.LENGTH_LONG).show();
                }
            });

            projectSpinner();
        }

        // Setup the dropdown spinner that allows the user to select the role.

        private void projectSpinner() {
            // Create adapter for spinner. The list options are from the String array it will use
            // the spinner will use the default layout
            ArrayAdapter projectSpinnerAdapter = ArrayAdapter.createFromResource(this,
                    R.array.projects, android.R.layout.simple_spinner_item);

            // Specify dropdown layout style - simple list view with 1 item per line
            projectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);

            // Apply the adapter to the project spinner
            mProjectSpinner.setAdapter(projectSpinnerAdapter);


            // Set the integer mSelected to the constant values
            mProjectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String selection = (String) parent.getItemAtPosition(position);

                    if(mProjectSpinner.getSelectedItem() == "This is Hint Text");

                    if (!TextUtils.isEmpty(selection)) {
                        if (selection.equals(getString(R.string.nextGEMS1_5))) {
                            mProject = 0 ;
                            return;
                        } else if (selection.equals(getString(R.string.nextGEMS1_6))) {
                            mProject = 1;
                            return;
                        } else if (selection.equals(getString(R.string.nextGEMS1_7))) {
                            mProject = 2;
                            return;
                        } else if (selection.equals(getString(R.string.nextGEMS1_8))) {
                            mProject = 3;
                            return;
                        } else if (selection.equals(getString(R.string.nextGEMS1_9))) {
                            mProject = 4;
                            return;
                        }
                        else mProject = 0;
                    }
                }

                // Because AdapterView is an abstract class, onNothingSelected must be defined
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    mProject = 0; // User
                }
            });
        }
    }

    ...

    activity_vote_main_admin.xml
    ...

    <?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="vertical">

        <androidx.viewpager.widget.ViewPager
            android:name="com.example.confidencevotefragmentrebuild.testFragment1"
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    ...
    activity_login.xml

    ...
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".LoginActivity"
        tools:showIn="@layout/activity_login">

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#5fb0c9"
            android:orientation="vertical"
            android:scrollbarAlwaysDrawVerticalTrack="true">

            <TextView
                android:id="@+id/login_title"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginTop="16dp"
                android:gravity="center_horizontal"
                android:text="LOGIN"
                android:textColor="#fff"
                android:textSize="20sp"
                android:textStyle="bold" />

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="500dp"
                android:background="#ffffff"
                android:elevation="4dp"
                android:orientation="vertical"
                android:padding="20dp"
                android:layout_below="@+id/login_title"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_marginTop="80dp">

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="450dp"
                    android:orientation="vertical"
                    android:paddingTop="30dp">

                    <com.google.android.material.textfield.TextInputLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="70dp">

                        <EditText
                            android:id="@+id/editText"
                            android:layout_width="fill_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="20dp"
                            android:drawableLeft="@drawable/usericon"
                            android:hint="User Name"
                            android:inputType="textEmailAddress"
                            android:maxLines="1" />
                    </com.google.android.material.textfield.TextInputLayout>

                    <com.google.android.material.textfield.TextInputLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">

                        <EditText
                            android:id="@+id/editText2"
                            android:layout_width="fill_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="16dp"
                            android:drawableLeft="@drawable/lock"
                            android:hint="Password"
                            android:inputType="textPassword"
                            android:maxLines="1" />
                    </com.google.android.material.textfield.TextInputLayout>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:paddingTop="5dp"
                        android:text="Forgot Password?" />

                    <Button
                        android:id="@+id/submit_button"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="22dp"
                        android:background="@drawable/action_buttom"
                        android:text="Sign in"
                        android:textAllCaps="false"
                        android:textColor="#fff"
                        android:textSize="18sp" />

                    <LinearLayout
                        android:layout_width="fill_parent"
                        android:layout_height="20dp"
                        android:orientation="horizontal"
                        android:paddingTop="1dp">

                        <TextView
                            android:id="@+id/attempts_text"
                            android:layout_width="wrap_content"
                            android:layout_height="25dp"
                            android:layout_gravity="center_horizontal"
                            android:paddingTop="1dp"
                            android:text="Number of attempts remaining: " />

                        <TextView
                            android:id="@+id/textView_Attempts"
                            android:layout_width="match_parent"
                            android:layout_height="25dp"
                            android:layout_gravity="center_horizontal"
                            android:paddingTop="1dp"
                            android:text="5" />
                    </LinearLayout>

                    <TextView
                        android:id="@+id/lnkRegister"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="1dp"
                        android:gravity="center"
                        android:paddingTop="30dp"
                        android:text="Register here"
                        android:textColor="#5fb0c9"
                        android:textSize="16sp" />
                </LinearLayout>

            </RelativeLayout>

            <ImageButton
                android:id="@+id/conferencevote_logo"
                android:layout_width="210dp"
                android:layout_height="180dp"
                android:layout_below="@+id/login_title"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="2dp"
                android:elevation="4dp"
                android:background="@drawable/rounded_button"
                android:src="@drawable/confvotenew"
                />
        </RelativeLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
    ...

    AdminFragemntyPagerAdapter
    ...
    package com.example.confidencevotefragmentrebuild;

    import androidx.fragment.app.Fragment;
    import androidx.fragment.app.FragmentManager;
    import androidx.fragment.app.FragmentPagerAdapter;

    public class AdminFragmentPagerAdapter extends FragmentPagerAdapter {


        public AdminFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return new testFragment1();
            } else if (position == 1) {
                return new testFragment2();
            } else {
                return new testFragment2();
            }
        }

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

    ...

aactivity_vote_user.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#5fb0c9"
    android:orientation="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true">

    <TextView
        android:id="@+id/vote_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:gravity="center_horizontal"
        android:text="USER VOTE"
        android:textColor="#fff"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="500dp"
        android:background="#ffffff"
        android:elevation="4dp"
        android:orientation="vertical"
        android:padding="20dp"
        android:layout_below="@+id/vote_title"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="80dp">

        <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="450dp"
                android:orientation="vertical"
                android:paddingTop="70dp">

                <com.google.android.material.textfield.TextInputLayout

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp">

                    <Spinner
                        android:id="@+id/spinner_project"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="20dp"
                        android:layout_marginLeft="25dp"
                        android:layout_marginRight="25dp"
                        android:hint="@string/spinner_hint"
                        android:maxLines="1"
                        android:singleLine="true"
                        android:backgroundTint="@color/attCobalt"
                        android:popupBackground="@color/myBlue"
                        android:dropDownSelector="@color/attBlue"

                        />
                </com.google.android.material.textfield.TextInputLayout
                    >

                <com.google.android.material.textfield.TextInputLayout

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center">

                    <RatingBar
                        android:id="@+id/rating_bar"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:stepSize="1.0"
                        android:layout_marginTop="40dp"
                        android:theme="@style/rating_bar"/>
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:paddingTop="5dp"
                        android:text="Vote and Submit" />

                    <FrameLayout
                        android:id="@+id/container"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
                </com.google.android.material.textfield.TextInputLayout>


                <Button
                    android:id="@+id/voteButton"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="22dp"
                    android:background="@drawable/action_buttom"
                    android:text="Submit"
                    android:textAllCaps="false"
                    android:textColor="#fff"
                    android:textSize="18sp" />
                />
            </LinearLayout>

            <com.google.android.material.bottomnavigation.BottomNavigationView
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>

        <ImageButton
            android:id="@+id/conferencevote_logo"
            android:layout_width="210dp"
            android:layout_height="180dp"
            android:layout_below="@+id/login_title"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="55dp"
            android:elevation="4dp"
            android:background="@drawable/rounded_button"
            android:src="@drawable/confvotenew"
            />

    </RelativeLayout>
    ...

My fragments are as follows.
...
package com.example.confidencevotefragmentrebuild;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

public class testFragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_vote_user, container, false);


    }


}
...

标签: android

解决方案


这个问题有两个原因:

  1. 您没有在“activity_vote_main_admin.xml”上声明任何按钮,这就是为什么您的视图没有与活动绑定并给出空指针异常的原因。

  2. 可能是您在片段 xml 上声明按钮并尝试将其与活动绑定。


推荐阅读