Java Android getApplicationContext()从上一类返回空对象

时间:2019-02-21 23:59:10

标签: java android

我正在尝试使用getApplicationContext()将用户从一个Java类传递给另一个Java类。不幸的是,它无法正常工作,并且返回null。我希望将用户信息从LoginActivity传递到CustomMapActivity。用户信息存储在Firebase中,这可能是个问题吗?

我相信清单是有条理的。请参见下面。

  <activity android:name=".ui.MapCustomActivity"></activity>
     <activity android:name=".ui.LoginActivity">
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
    <activity android:name=".ui.RegisterActivity" />
     <activity android:name=".ui.ProfileActivity" />
    <activity android:name=".ui.MapCustomActivity"></activity>

下面是LoginActivity,

public class LoginActivity extends AppCompatActivity implements
        View.OnClickListener
      {
       @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mEmail = findViewById(R.id.email);
        mPassword = findViewById(R.id.password);
        mProgressBar = findViewById(R.id.progressBar);

        setupFirebaseAuth();
        findViewById(R.id.email_sign_in_button).setOnClickListener(this);
        findViewById(R.id.link_register).setOnClickListener(this);

        hideSoftKeyboard();
    }




    private void showDialog(){
        mProgressBar.setVisibility(View.VISIBLE);

    }

    private void hideDialog(){
        if(mProgressBar.getVisibility() == View.VISIBLE){
            mProgressBar.setVisibility(View.INVISIBLE);
        }
    }




      private void setupFirebaseAuth(){
        Log.d(TAG, "setupFirebaseAuth: started.");

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                //user = null;
                if (user != null) {
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getEmail());
                    Toast.makeText(LoginActivity.this, "Authenticated with: " + user.getEmail(), Toast.LENGTH_SHORT).show();

                    FirebaseFirestore db = FirebaseFirestore.getInstance();
                    FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                            .setTimestampsInSnapshotsEnabled(true)
                            .build();
                    db.setFirestoreSettings(settings);

                    DocumentReference userRef = db.collection(getString(R.string.collection_users))
                            .document(user.getUid());

                    userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                            if(task.isSuccessful()){
                                Log.d(TAG, "onComplete: successfully set the user client." + task.getResult());
                                User user = task.getResult().toObject(User.class);
                                ((UserClient)(getApplicationContext())).setUser(user);
                            }
                        }
                    });

                    Intent intent = new Intent(LoginActivity.this, MapCustomActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();

                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
                // ...
            }
        };
      }

下面是MapCustomActivity:

public class MapCustomActivity extends AppCompatActivity {

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_map_custom);

        photoview2 = (ImageView) findViewById(R.id.limerickMapImageView);
         mAvatarImage = (ImageView) findViewById(R.id.imageChooseAvatar);

        photoview2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ImageView view = (ImageView) v;
                view.bringToFront();
                viewTransformation(view, event);
                return true;
            }
        });
        retrieveProfileImage();

    }
     private void retrieveProfileImage(){
        RequestOptions requestOptions = new RequestOptions()
                .error(R.drawable.cwm_logo)
                .placeholder(R.drawable.cwm_logo);

        int avatar = 0;

        try{

            avatar = Integer.parseInt(((UserClient)getApplicationContext()).getUser().getAvatar());
        }catch (NumberFormatException e){
            Log.e(TAG, "retrieveProfileImage: no avatar image. Setting default. " + e.getMessage() );
        }

        Glide.with(MapCustomActivity.this)
                .setDefaultRequestOptions(requestOptions)
                .load(avatar)
                .into(mAvatarImage);
    }

下面是UserClient类

public class UserClient extends Application {

    private User user = null;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}

4 个答案:

答案 0 :(得分:2)

要使用意图将数据从一个活动传递到另一个活动,请确保已按照以下步骤操作。

  • 第1步在源中创建一个新的显式或隐式Intent对象 活动。
  • 步骤2调用 intent.putExtra(字符串键,对象数据)方法以在其中保存数据。
  • 第3步在源活动中调用startActivity(intent)方法,以将意图传递给android操作系统。
  • 第4步,在目标活动中调用getIntent()方法。

如果您认为我很想念您第2步

答案 1 :(得分:0)

您正在使用getApplicationContext,但也许您正在尝试使用Activity中的getApplication方法。 我不建议使用这种方法将对象从一个活动传递到另一个活动。您应该使用Intent对象。看看the official docs

答案 2 :(得分:0)

您可以使用bundle来提供活动之间的信息

Bundle bundle = new Bundle();
bundle.putInt("value_name", 0);// 0 = value
bundle.putString("value_name", "text"); // Text = value string

Intent intent = new Intent(this, SecondActivty.class);
intent.putExtras(bundle);
startActivity(intent);

参加第二个活动

public class SecondActivty extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_activty);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    int value = savedInstanceState.getInt("value_name");
}

答案 3 :(得分:0)

在您当前的活动中,创建一个新的Intent:

String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
i.putExtra("key",value);
startActivity(i);

然后在新的活动中,检索这些值:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    //The key argument here must match that used in the other activity
}

通过这种技术,您将能够在活动中传递变量