(2016.3.15 更新)
上周我遇到了一个奇怪的问题,我想和你讨论一下。
问题场景:</p>
AppCompatActivity 中有一个 searchView。每当文本发生变化时,Activity 中的 Fragment 都会通过“ getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, fragment).commit();
”替换。
在片段中,有一个名为 SearchThread 的线程,它将在onActivityCreated()
. 言归正传,里面有getActivity().runOnUiThread(new Runnable{...})
方法。不管“new Runnable()”里面是什么,当searchView的文本快速变化的时候都会出现NullPointerException,导致这个fragment频繁的重新建立。
日志猫:
03-15 20:12:25.912/cn.example.app E/AndroidRuntime: FATAL EXCEPTION: Thread-10820
Process: cn.example.app, PID: 31532
java.lang.NullPointerException
at cn.example.app.homepage.GymFragment$searchThread.run(GymFragment.java:257)
at java.lang.Thread.run(Thread.java:841)
但是,如果我使用 sendMessage(searchHandler.obtain...) 而不是 runOnUiThread,一切都会顺利!!
GymFragment.Java:</p>
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
new Thread(new SearchThread()).start();
}
class SearchThread implements Runnable{
@Override
public void run() {
String s = "";
try {
Thread.sleep(4000);
} catch (Exception e) {;}
//searchHandler.sendMessage(searchHandler.obtainMessage(0, s));//Correct
getActivity().runOnUiThread(new Runnable() { //Throw NullPointer Exception or pool-1-thread-1 (with ExecutorService)
@Override
public void run() {
;
}
});
}
}
搜索活动.Java:
class queryChangeListener implements SearchView.OnQueryTextListener{
...
@Override
public boolean onQueryTextChange(String newText) {
currentSearchTip = newText;
if (newText != null && newText.length() > 0) {
searchDelayed(newText);
}
return true;
}
}
private Handler searchHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg == null)
return;
String searchText = (String) msg.obj;
if (currentSearchTip != null && currentSearchTip.isEmpty()==false) {
GymFragment fragment = GymFragment.newInstance(searchText);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, fragment).commit();
}
}
};
private ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(10);
private String currentSearchTip;
public void searchDelayed(String newText) {
scheduledExecutor.schedule(new SearchThread(newText),500, TimeUnit.MILLISECONDS);
}
class SearchThread implements Runnable {
String newText;
public SearchThread(String newText){
this.newText = newText;
}
public void run() {
if (newText != null && newText.equals(currentSearchTip)) {
searchHandler.sendMessage(searchHandler.obtainMessage(0, newText));
}
}
}
解决方案:</p>
1) 注释掉"getActivity()...",改用注释掉的"sendMessage(searchhandler.obtain..)"。
2)在运行getActivity().runOnUiThread()之前,先判断getActivity()==null。
2016.3.14:
[一些有趣的事情:)]
- “runOnUiThread”的源代码
runOnUIThread(Runnable r)的源码:</p>
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
实际上,runOnUiThread 调用 mHandler.post(Runnable r)。
让我们看看 post(Runnable r) 中的内容:
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
而在getPostMessage(Runnable r)中:</p>
private final Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
然后在Message.obtain()中:</p>
public final Message obtainMessage() {
return Message.obtain(this);
}
public static Message obtain(Message orig) {
Message m = obtain();
m.what = orig.what;
m.arg1 = orig.arg1;
m.arg2 = orig.arg2;
m.obj = orig.obj;
m.replyTo = orig.replyTo;
if (orig.data != null) {
m.data = new Bundle(orig.data);
}
m.target = orig.target;
m.callback = orig.callback;
return m;
}
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
sPoolSize--;
return m;
}
}
return new Message();
}
2.“sendMessage(Message msg)”源码:</p>
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
在这里我们可以看到,sendMessage(Message msg) 的实现几乎等同于 post(Runnable r) 的实现。差异可能与 getPostMessage(Runnable r) 有关。
所以,简而言之,当我同时执行时,实际导致正确执行 searchHandler.SendMessage(searchHandler.obtainMessage(0,str)),而导致 getActivity().runOnUiThread(new Runnable{...}) 异常的原因反复执行?非常感谢!