1

我正在尝试使用我的 MVVM 模式登录活动来显示初始屏幕。我的启动画面确实可以正常工作,但是当它尝试完成并启动 LoginActivity 时,应用程序崩溃了。我收到此错误如下。

请帮我解决这个问题。我需要在我的项目中有一个带有 MVVM 模式和用于 LoginActivity 的房间数据库的 slapsh 屏幕。非常欢迎提供解释或代码示例。

我的飞溅活动

public class SplashActivity extends AppCompatActivity {

public void onAttachedToWindow() {
    super.onAttachedToWindow();
    Window window = getWindow();
    window.setFormat(PixelFormat.RGBA_8888);
}

/**
 * Called when the activity is first created.
 */
Thread splashTread;

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

    StartAnimations();
}

private void StartAnimations() {
    Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
    anim.reset();
    LinearLayout l = findViewById(R.id.splash_layout);
    l.clearAnimation();
    l.startAnimation(anim);

    anim = AnimationUtils.loadAnimation(this, R.anim.translate);
    anim.reset();
    ImageView iv = findViewById(R.id.splash);
    iv.clearAnimation();
    iv.startAnimation(anim);

    splashTread = new Thread() {
        @Override
        public void run() {
            try {
                int waited = 0;
                // Splash screen pause time
                while (waited < 3500) {
                    sleep(100);
                    waited += 100;
                }
                Intent intent = new Intent(SplashActivity.this,
                        LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intent);
                SplashActivity.this.finish();
            } catch (InterruptedException e) {
                // do nothing
            } finally {
                SplashActivity.this.finish();
            }

        }
    };
    splashTread.start();
}
}

我的登录活动

public class LoginActivity extends AppCompatActivity {

private LoginViewModel loginViewModel;
private View mProgressView;
private View mLoginFormView;

private ActivityLoginBinding binding;

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

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

    ActivityLoginBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
    //get the view model
    loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
    binding.setUser(loginViewModel);

    // The observer updates the UI when Login Operation is successful
    loginViewModel.getUser().observe(this, userResponse -> {
        if (userResponse != null) {
            Toast.makeText(LoginActivity.this, "Login success", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();

        } else {
            Log.d("LoginActivity", "value user is null");
            // Show ERROR
        }
    });

    binding.loginButton.setOnClickListener (
            (
                    View view) ->

            {
                loginViewModel.onBtnLoginClick();

            });
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    mLoginFormView.animate().setDuration(shortAnimTime).alpha(
            show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    });

    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
    mProgressView.animate().setDuration(shortAnimTime).alpha(
            show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    });
}

}

我的登录视图模型

public class LoginViewModel extends ViewModel {

private boolean errorMsg = true;
private Validations validations;

// Create a LiveData
private LiveData<User> userResponse;

public static final ObservableField<String> username = new ObservableField<>();
public static final ObservableField<String> password = new ObservableField<>();

public static final ObservableField<String> errorUsername = new ObservableField<>();
public static final ObservableField<String> errorPassword = new ObservableField<>();

private UserRepository userRepository;

public LoginViewModel(Context mContext) {

    userRepository = new UserRepository(mContext);
    username.set("ccuser");
    password.set("67890");

    userResponse = userRepository.getUser();

    validations=new Validations();

}

public LiveData<User> getUser() {
    return userResponse;
}

public void onBtnLoginClick() {

//        attemptLogin();
    if (validateInputs()) {
        userRepository.loginUser(username.get(), password.get());
    }
}
@BindingAdapter("error")
public static void setError(EditText editText, Object strOrResId) {
    if (strOrResId instanceof Integer) {
        editText.setError(
                editText.getContext().getString((Integer) strOrResId));
    } else {
        editText.setError((String) strOrResId);
    }
}

@BindingAdapter("onFocus")
public static void bindFocusChange(EditText editText, View.OnFocusChangeListener onFocusChangeListener) {
    if (editText.getOnFocusChangeListener() == null) {
        editText.setOnFocusChangeListener(onFocusChangeListener);
    }
}

//--
public boolean validateInputs() {
    boolean isValid = true;

    if (username.get() == null || !Validations.isUserNameValid(username.get())) {
        errorUsername.set(String.valueOf(R.string.error_invalid_username));
        isValid = false;
    } else {
        errorUsername.set(null);
    }
    if (password.get() == null || password.get().length() < 8 && !Validations.isPasswordValid(password.get())) {
        errorPassword.set(String.valueOf(R.string.error_incorrect_password));
        isValid = false;
    } else {
        errorPassword.set(null);
    }
    return isValid;
}
}

我得到的错误

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.comcredit.ccui.cclogin, PID: 19969 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.comcredit.ccui.cclogin/com.comcredit.ccui.cclogin.view .LoginActivity}:java.lang.RuntimeException:无法在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2858) 在 android.app.ActivityThread.handleLaunchActivity 创建类 com.comcredit.ccui.cclogin.view_model.LoginViewModel 的实例(ActivityThread.java:2933) 在 android.app.ActivityThread.-wrap11(Unknown Source:0) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1612) 在 android.os.Handler.dispatchMessage(Handler. java:105) 在 android.os.Looper.loop(Looper.java:164) 在 android。app.ActivityThread.main(ActivityThread.java:6710) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 在 com. android.internal.os.ZygoteInit.main(ZygoteInit.java:770) 原因:java.lang.RuntimeException:无法在 android.arch.lifecycle.ViewModelProvider 创建类 com.comcredit.ccui.cclogin.view_model.LoginViewModel 的实例$NewInstanceFactory.create(ViewModelProvider.java:153) 在 android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) 在 android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) 在 android。 com.comcredit 上的 arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102)。ccui.cclogin.view.LoginActivity.onCreate(LoginActivity.java:45) 在 android.app.Activity.performCreate(Activity.java:6980) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 在 android.app .ActivityThread.performLaunchActivity(ActivityThread.java:2811) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2933) 在 android.app.ActivityThread.-wrap11(Unknown Source:0) 在 android.app.ActivityThread$H。 handleMessage(ActivityThread.java:1612) 在 android.os.Handler.dispatchMessage(Handler.java:105) 在 android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java :6710) 在 java.lang.reflect.Method。com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 处的调用(本机方法) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) 引起:java。 lang.InstantiationException:java.lang.Class 在 android.arch 的 android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:151) 的 java.lang.Class.newInstance(Native Method) 没有零参数构造函数。 lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com .comcredit.ccui.cclogin.view.LoginActivity.onCreate(LoginActivity.java:45) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2811) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 在 android.app.Activity.performCreate(Activity.java:6980)。 app.ActivityThread.handleLaunchActivity(ActivityThread.java:2933) 在 android.app.ActivityThread.-wrap11(Unknown Source:0) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1612) 在 android.os.Handler .dispatchMessage(Handler.java:105) 在 android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java:6710) 在 java.lang.reflect.Method.invoke(本机方法)在 com.android.internal.os.Zygote$MethodAndArgsCaller。在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) 处运行(Zygote.java:240) 

4

2 回答 2

0

this在您的 Intent 声明中是指您的视图模型。尝试传递完整的活动名称。

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
于 2018-12-20T07:16:54.280 回答
0

使用此代码:

new Handler().postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            Intent intent = new Intent(SplashActivity.this,
                    LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(intent);
            SplashActivity.this.finish();
        }
    },3500);

替换您的代码:

splashTread = new Thread() {
    @Override
    public void run() {
        try {
            int waited = 0;
            // Splash screen pause time
            while (waited < 3500) {
                sleep(100);
                waited += 100;
            }
            Intent intent = new Intent(SplashActivity.this,
                    LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(intent);
            SplashActivity.this.finish();
        } catch (InterruptedException e) {
            // do nothing
        } finally {
            SplashActivity.this.finish();
        }

    }
};
splashTread.start();
于 2018-12-20T07:30:00.150 回答