使用ViewModel和Databinding验证表单数据的最佳方法是什么?
我有一个简单的Sign-Up活动,该活动链接绑定布局和ViewModel
class StartActivity : AppCompatActivity() {
private lateinit var binding: StartActivityBinding
private lateinit var viewModel: SignUpViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(this, SignUpViewModelFactory(AuthFirebase()))
.get(SignUpViewModel::class.java);
binding = DataBindingUtil.setContentView(this, R.layout.start_activity)
binding.viewModel = viewModel;
signUpButton.setOnClickListener {
}
}
}
Run Code Online (Sandbox Code Playgroud)
ViewModel4 ObservableFields和signUp()在向服务器提交数据之前应该验证数据的方法。
class SignUpViewModel(val auth: Auth) : ViewModel() {
val name: MutableLiveData<String> = MutableLiveData()
val email: MutableLiveData<String> = MutableLiveData()
val password: MutableLiveData<String> = MutableLiveData()
val passwordConfirm: MutableLiveData<String> = MutableLiveData()
fun signUp() {
auth.createUser(email.value!!, password.value!!)
}
} …Run Code Online (Sandbox Code Playgroud) validation android kotlin android-databinding android-viewmodel
我是 Kotlin 协程的新手,并试图了解监督。正如文档所说:
子节点的失败或取消不会导致主管作业失败,也不会影响其其他子节点。
好的,我已经为 JVM 编写了以下代码:
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val supervisorScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
// Coroutine #1
supervisorScope.launch {
println("Coroutine #1 start")
delay(100)
throw RuntimeException("Coroutine #1 failure")
}
// Coroutine #2
supervisorScope.launch {
for (i in 0 until 5) {
println("Coroutine #2: $i")
delay(100)
}
}
supervisorScope.coroutineContext[Job]!!.children.forEach { it.join() }
}
Run Code Online (Sandbox Code Playgroud)
这里一切都很好,Coroutine #1失败既不会影响父级,也不会影响Coroutine #2. 这就是监督的目的。输出与文档一致:
Coroutine #1 start
Coroutine #2: 0
Coroutine #2: 1
Exception in thread "DefaultDispatcher-worker-1" java.lang.RuntimeException: Coroutine …Run Code Online (Sandbox Code Playgroud) 我有一个需要进行单元测试的服务类。该服务具有上载方法,该方法又调用其他服务(自动装配的Bean)来更新数据库。我需要模拟其中一些服务,并按原样执行。
@Service
public class UploadServiceImpl implements UploadService{
@Autowired
private ServiceA serviceA;
@Autowired
private ServiceB serviceB;
public void upload(){
serviceA.execute();
serviceB.execute():
//code...
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我需要模拟ServiceA,但我希望ServiceB照常运行并执行其功能。我的Junit测试看起来像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=Swagger2SpringBoot.class)
public class UploadServiceTest {
@Mock
private ServiceA serviceA;
@InjectMocks
private UploadServiceImpl uploadService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testUpload(){
uploadService.upload();
}
Run Code Online (Sandbox Code Playgroud)
当我执行此我得到NPE在serviceB.execute();在UploadServiceImpl。
可能是什么问题呢?
注意:我没有指定模拟对象的行为,因为我并不在乎,模拟对象的默认行为也不执行任何操作。
谢谢!
我想在使用它们之前检查方法的所有参数是否都有正确的信息.像这样的东西:
public method(MyType param1)
{
try
{
if(param1 == null)
{
throw new ArgumentNullException("Error1");
}
if(param1.Property1 == null)
{
throw new ArgumentNullException("Error2");
}
if(param1.Property1.Amount <= 0)
{
throw new ArgumentException("Error3");
}
...
//Do what I need with the parameter
}
catch { throw; }
}
Run Code Online (Sandbox Code Playgroud)
然而,在这篇文章中,有人评论说将异常作为正常流程抛出并不是一个好主意,但我不确定是否是这种情况,因为如果我必须检查参数,还有例如ArgumentNullException和ArgumentException它似乎可以在参数出现问题时被抛出,这让我想知道它是否真的是一个糟糕的方法,我评论的例子.
另一个用户给出的另一个原因是异常消耗4000-8000个CPU周期.好吧,在我的情况下的目标是知道参数是否有一些错误,并且如果应用程序按预期工作,则永远不会抛出异常,因此在实践中,如果应用程序没有错误,那么性能不会减少.
总而言之,我想知道在继续该过程之前如何处理参数检查的最佳方法.
谢谢.
我正在尝试学习kotlin,我想将我的一个android项目从java转换为kotlin.但我有一个问题
override fun onResponse(call: Call<List<CitySearch>>?, response: Response<List<CitySearch>>?) {
if(response != null && response.isSuccessful) {
val list = response.body()
cityAdapter.clear()
if(list != null && !list.isEmpty()){
cityAdapter.addAll(list)
listView.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
cityName.visibility = View.GONE
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误操作不支持只读集合在kotlin.collections.EmptyList.clear()与cityAdapter.clear()的行上我不知道如何解决它.
对于所有项目,请检查
我有一个打电话的程序fprintf.在Visual Studio 2013中,编译和执行的所有内容都没有错误和警告.现在该项目已迁移到Visual Studio 2015(没有任何更改),我的大多数fprintf调用都收到以下警告:
C4474: too many arguments passed for format string
Run Code Online (Sandbox Code Playgroud)
大多数这些警告都指向以下代码行:
fprintf (stderr,"Missing header file name. Formant is :\n", pArg);
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?我是否需要重写我的代码,或者导致这些警告的项目设置是否有问题?
我看到,在这篇 MSDN文章中,对这些函数进行了更改:
所有printf和scanf函数的定义都已内联移入stdio.h,conio.h和其他CRT头文件中.
这与我的问题有关吗?这对VS 2015来说只是一个无害的变化,还是存在一个潜在的崩溃导致的陷阱?
为什么新Spliterators类出现在Java 8中?从Java 8开始,我们可以向static接口添加方法.由于Spliterators类只有静态方法,所以在其中声明其所有方法都不会更简单Spliterator interface?
关于Collectors/Collector对的同样问题.
谢谢.
我有一个列表,items我想根据 开始不同的活动item,当我单击它时会打开正确的活动,但是当我尝试从搜索视图栏中搜索列表项时,它会打开错误的活动。
listView = (ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView1);
String[] values = new String[]{item1,item2,item3,item4,}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2, android.R.id.text1, values);
listView.setAdapter(adapter);
//linking from 1 item to other activity stars with if options//
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
if (position == 4) {
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
}
}); …Run Code Online (Sandbox Code Playgroud) 我是初学者。
首先说我看过以前的帖子但没有回答。
我尝试测试音频播放器,但是当我尝试运行该应用程序时,由于空对象引用,它立即崩溃。
这是 Logcat:(此日志说:错误在 Java 代码的第 28 行)
EXCEPTION: main
Process: ir.pluto.mediaplayer, PID: 19100
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ir.pluto.mediaplayer/ir.pluto.mediaplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:92)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.View.<init>(View.java:4054)
at android.view.View.<init>(View.java:4186) …Run Code Online (Sandbox Code Playgroud) 我不知道为什么这个简单的代码不起作用。我计划将字符串与允许的模式进行匹配。该字符串只能包含a-z, A-Z, 0-9, _(下划线), .(点), -(hiphen)。
下面是代码:
var profileIDPattern = /[a-zA-Z0-9_.-]./;
var str = 'Heman%t';
console.log('hemant',profileIDPattern.test(str));
Run Code Online (Sandbox Code Playgroud)
代码为以下字符串记录“true”,尽管这些字符串与模式不匹配。
'Heman%t' -> true
'#Hemant$' -> true
Run Code Online (Sandbox Code Playgroud)
我不知道是什么问题。
android ×5
java ×4
kotlin ×3
c ×1
c# ×1
c++ ×1
exception ×1
java-8 ×1
java-stream ×1
javascript ×1
listview ×1
mockito ×1
printf ×1
regex ×1
searchview ×1
spring-boot ×1
validation ×1