gpt4 book ai didi

测试类中的 android.view.ViewRootImpl$CalledFromWrongThreadException

转载 作者:行者123 更新时间:2023-11-28 21:10:12 28 4
gpt4 key购买 nike

我正在为一个 Android 应用开发一个测试类,我收到了一个 android.view.ViewRootImpl$CalledFromWrongThreadException。该代码假设模拟输入到文本字段中。当调用语句 searchText.setText("hi"); 时,在方法 testSearch() 中抛出此异常。我不知道为什么会这样,我想修复它。这是代码:

package com.example.guy.smsclassproject;

import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;

/**
* Created by Guy on 11/16/2015.
*/
public class DraftsActivityTest2 extends ActivityInstrumentationTestCase2<DraftsActivity>
{
private EditText searchText;
private Button searchButton;
private DraftsDatabase draftsDatabase;
ArrayList<MessageObject> messagesToBeDisplayed;
DraftsActivity tester;
public DraftsActivityTest2()
{
super(DraftsActivity.class);
}

@Override
public void setUp() throws Exception
{
draftsDatabase = new DraftsDatabase();
MessageObject messageObject1 = new MessageObject("hi", "5554", true);
MessageObject messageObject2 = new MessageObject("hi hi", "5555554", true);
MessageObject messageObject3 = new MessageObject("sup", "5435555554", true);
draftsDatabase.addMessage(messageObject1);
draftsDatabase.addMessage(messageObject2);
draftsDatabase.addMessage(messageObject3);
messagesToBeDisplayed = draftsDatabase.getAllTexts();
tester = getActivity();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
searchText = (EditText) tester.findViewById(R.id.searchText);
searchButton = (Button) tester.findViewById(R.id.searchButton);
}

@SmallTest
public void testSearch() {
//The problem occurs here:
searchText.setText("hi");
searchButton.performClick();
messagesToBeDisplayed = draftsDatabase.getMessagesByKey(searchText.getText().toString());
assertEquals("Messages with the word hi", 2, messagesToBeDisplayed.size());

}

最佳答案

问题是您只能从主 UI 线程修改小部件...您可以尝试添加 UiThreadTesttestSearch 的注释,这将导致它在主线程中运行。

关于测试类中的 android.view.ViewRootImpl$CalledFromWrongThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33811208/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com