簡體   English   中英

來回移動活動時Android意圖返回null

[英]Android intent returning null when moving back and forth of activities

我有一個應用程序,用戶可以在其中創建/登錄帳戶,當用戶登錄時,我將他們的有效電子郵件作為意圖傳遞給 main/landing activity 。

我還有另一個用戶配置文件活動,我從中傳遞了登陸活動(用戶電子郵件)的意圖。

使用用戶電子郵件,我創建了查詢以獲取所有用戶項目(這是一種 PM 工具)-在我的登陸活動中,我還有一個片段,我在其中使用基於用戶電子郵件的這些查詢。

在我的用戶個人資料活動中,我還創建了查​​詢以獲取用戶詳細信息(姓名、電子郵件等),以便在他們的個人資料中顯示他們可以更改的地方等。

========

問題是,最初當我使用有效的詳細信息登錄並被帶到登陸活動時,我得到了很棒的用戶項目,我還可以導航到用戶個人資料活動,我得到了用戶的詳細信息,這就是我想。

然后,當我回到登陸活動時,從登錄活動傳遞的意圖(用戶電子郵件)不再有效,因此我沒有從我的數據庫查詢中得到任何結果,當我回到個人資料活動時,意圖是null 所以我不能再獲取當前用戶了。

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.ppmtoolmobile.model.User.getFirstName()' on a null object reference

我想要一些關於如何處理這個問題的建議,以避免在來回移動時出現 NPE。


我刪除了組件的變量以使其更具可讀性,但我已經將它們全部初始化等等。

登陸Activity / ProjectActivity.java


public class ProjectActivity extends AppCompatActivity implements View.OnClickListener, MyRecyclerAdapter.OnProjectClickListener {


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project);

        // My dao implementation with DB queries
        daoHelper = new DaoHelper(this);

        // getting current username through intent from LoginActivity.class
        authenticatedUser = getIntent().getStringExtra("authenticatedUser");

        Toast.makeText(this, "project activity: " + authenticatedUser, Toast.LENGTH_SHORT).show();

        // current user id
        userId = daoHelper.getCurrentUserId(authenticatedUser);

        // Getting users first name and amount of projects (This will be displayed in the heading of the main screen)
        userFirstName = daoHelper.getCurrentUserFirstName(authenticatedUser);
        projectCount = daoHelper.getProjectCount(userId);

        welcomeUserTextView1.setText("Welcome " + userFirstName + ", " + userId);
        displayUserProjectCountTextView.setText("You currently have " + projectCount + " projects");


        loadFragment(new ProjectFragment());

        // Perform item selected listener
        bottomNavView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch(item.getItemId())
                {
                    case R.id.nav_profile:
                        Intent goToProfileActivityIntent = new Intent(ProjectActivity.this, ProfileActivity.class);
                        goToProfileActivityIntent.putExtra("authenticatedUser", authenticatedUser);
                        startActivity(goToProfileActivityIntent);

                        overridePendingTransition(0,0);
                        return true;
                    case R.id.nav_home:
                        return true;
                    case R.id.nav_settings:
                        startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
                        overridePendingTransition(0,0);
                        return true;
                }
                return false;
            }
        });



    }

}


ProfileActivity.java

public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
    

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

        // getting current username through intent from ProjectActivity.class
        authenticatedUser = getIntent().getStringExtra("authenticatedUser");

        Toast.makeText(this, "profile activity: " + authenticatedUser, Toast.LENGTH_SHORT).show();
        daoHelper = new DaoHelper(this);

        loadUserDetails();

        // Perform item selected listener
        bottomNavView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch(item.getItemId())
                {
                    case R.id.nav_home:
                        startActivity(new Intent(getApplicationContext(), ProjectActivity.class));
                        overridePendingTransition(0,0);
                        return true;
                    case R.id.nav_profile:
                        return true;
                    case R.id.nav_settings:
                        startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
                        overridePendingTransition(0,0);
                        return true;
                }
                return false;
            }
        });
    }

    private void loadUserDetails() {
        // I get NPE here when moving from ProjectActivity for the second time
        User user = daoHelper.getUserDetails(authenticatedUser);
        profileFirstNameEditText.setText(user.getFirstName());
        profileLastNameEditText.setText(user.getLastName());
        profileEmailAddressEditText.setText(user.getEmailAddress());



    }



}

DaoHelper.java 方法

// get user details
    public User getUserDetails(String theEmailAddress) {
        SQLiteDatabase db = this.getReadableDatabase();
        User user = null;
        Cursor cursor = db.query(USER_TABLE,// Selecting Table
                new String[]{COLUMN_USER_ID, COLUMN_USER_FIRST_NAME, COLUMN_USER_LAST_NAME, COLUMN_USER_EMAIL_ADDRESS, COLUMN_USER_PASSWORD},//Selecting columns want to query
                COLUMN_USER_EMAIL_ADDRESS + " = ?",
                new String[]{String.valueOf(theEmailAddress)},//Where clause
                null, null, null);

        System.out.println("cursor count: " + cursor.getCount());

        if(cursor.moveToNext()) {
            long userId = cursor.getLong(0);
            String firstName = cursor.getString(1);
            String lastName = cursor.getString(2);
            String emailAddress = cursor.getString(3);
            String password = cursor.getString(4);

            user = new User(userId, firstName, lastName, emailAddress, password);
        }

        return user;
    }

    // get project count of user
    public int getProjectCount(long userId) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + PROJECT_TABLE + " WHERE " + COLUMN_USER_PROJECT_FK + " = ?", new String[]{String.valueOf(userId)})
        return cursor.getCount();
    }

    // get all of users projects
        @RequiresApi(api = Build.VERSION_CODES.O)
    public List<Project> getUserProjects(long userId) {

        SQLiteDatabase db = this.getReadableDatabase();
        List<Project> projectList = new ArrayList<>();

        Cursor cursor = db.rawQuery("SELECT * FROM " + PROJECT_TABLE + " WHERE " + COLUMN_USER_PROJECT_FK + " = ?", new String[]{String.valueOf(userId)});

        while(cursor.moveToNext()) {
            long id = cursor.getLong(0);
            String title = cursor.getString(1);
            String description = cursor.getString(2);
            String dateCreated = cursor.getString(3);
            String dateDue = cursor.getString(4);

            DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
            LocalDateTime dateCreatedFormatted = LocalDateTime.parse(dateCreated, formatter);
            LocalDateTime dateDueFormatted = LocalDateTime.parse(dateDue, formatter);

            String priority = cursor.getString(5);
            String checklist = cursor.getString(6);
            int theUserId = cursor.getInt(7);

            Project project = new Project(id, title, description, dateCreatedFormatted, dateDueFormatted, priority, checklist, theUserId);

            projectList.add(project);
        }
        return projectList;
    }



登錄后的初始狀態 移動到配置文件活動然后返回項目活動時的狀態

這里的問題是,您正在 ProfileActivity 的bottomNavViewonNavigationItemSelected偵聽器中啟動另一個 ProjectActivity 實例,該偵聽器沒有參數( startActivity(new Intent(getApplicationContext(), ProjectActivity.class));
這就是為什么在 ProjectActivity 的第二個實例中,參數authenticatedUser沒有值並返回空字符串。

您可以通過在ProfileActivity類中修改 bottomNavView 的 onNavigationItemSelected 偵聽器的代碼來解決此問題。 在 ProfileActivity 類中替換 id R.id.nav_home 的 switch case 邏輯,如下所示

case R.id.nav_home:
    finish();
    overridePendingTransition(0,0);
    return true;

或者,如果您想保留同一活動的多個實例(ProjectActivity 和 ProfileActivity),那么您可以在 ProfileActivity 的 bottomNavView 的 itemSelectedListener 中為 Intent 實例添加參數。 在這種情況下,您的代碼將如下所示

case R.id.nav_home:
    Intent goToProjectActivity = new Intent(ProfileActivity.this, ProjectActivity.class);
    goToProjectActivity.putExtra("authenticatedUser", authenticatedUser);
    startActivity(goToProjectActivity);
    overridePendingTransition(0,0);
    return true;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM