ViewPager片段中的TextView随机崩溃应用程序NullPointerException:尝试调用虚拟方法vo



摘要

  1. 首先我描述上下文,即我试图做什么

  2. 其次,我向您解释我在哪些情况下遇到错误以及它是什么(它是当前行为)

  3. 第三,我向您解释预期行为

  4. 然后我向您解释如何复制错误

  5. 最后,我向您展示了可导致错误的最小可执行代码


上下文

我正在使用API中其他人之间可用的小部件AutoScrollTextViewhttps://github.com/ronghao/AutoScrollTextView.AutoScrollTextView是一个TextView,它可以自动垂直滚动,而且,如果文本太长,可以水平滚动。因此,AutoScrollTextView可以包含至少一个要自动滚动的文本(请参阅GitHub存储库中的插图)。

当前行为:错误

  1. 如果我在主活动中使用一个AutoScrollTextView,我不会看到任何错误。如果我在主活动的片段中使用它,我想情况也是如此(我没有测试它)
  2. 如果我在ViewPager的至少两个片段中的每一个片段中使用一个AutoScrollTextView(同一片段类的两个实例用于Viewpager),并且每个AutoScrollTextView至少要自动滚动一个文本,则应用程序将崩溃并出现以下错误(NB:ViewPager属于主活动):

E/AndroidRuntime:致命异常:main流程:com.example.mApplication,PID:2814java.lang.NullPointerException:尝试对null对象引用调用虚拟方法"void android.view.view.sendAccessibilityEventUnchecked(android.vview.accessibility.Event)"在android.view.ViewRootImpl$SendWindowContentChangedAccessibilityEvent.run(ViewRootImpl.java:9304)在android.os.Handler.handleCallback上(Handler.java:789)在android.os.Handler.dispatchMessage上(Handler.java:98)在android.os.Looper.loop(Looper.java:164)在android.app.ActivityThread.main上(ActivityThreads.java:6944)位于java.lang.reflect.Method.ioke(本机方法)网址:com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)网址:com.android.internal.os.ZygoteInit.main(ZygoteNit.java:1374)

然而,该错误很难触发:

  1. 有时,它会在主活动的片段启动后立即触发
  2. 有时,在主活动的片段中触发之前会有一个随机延迟
  3. 有时,也许它没有被触发(或者我提前关闭了应用程序)

正如您所看到的,没有任何导致此次崩溃的线路指示。

我所做的调试

  1. 我已经取了这个库,并隔离了导致这个bug的最小部分。

  2. 我已经设置了最小可执行应用程序,其中只有主活动ViewPager和片段(Viewpager使用了同一片段类的2个实例)。

  3. 我已经用库的独立部分设置了这个最小的可执行应用程序。你会在下面找到来源(即使有"很多"文件,每个文件都经过了最小化,并且只包含严格的最小行,以便你能够重现错误)。此外:根据我给你的消息来源,你看不到文本滚动(也看不到任何文本)是完全正常的。这是因为我已经完全隔离了触发bug的API部分,滚动文本与这个错误无关,所以它不是我隔离的源代码的一部分。

  4. 我试着使用安卓的Timer而不是Handler,但错误仍然存在。

  5. MarqueeTextView::scrollTo(currentScrollPos, 0);似乎触发了此错误。

预期行为

正常情况下,应用程序当然不应该崩溃。换句话说,不应该有任何触发错误(尤其是我上面引用的那个)。根据我给你的消息来源,你看不到文本滚动(也看不到任何文本)是完全正常的。这是因为我已经完全隔离了触发bug的API部分,滚动文本与这个错误无关,所以它不是我隔离的源代码的一部分。

如何重现此错误

下面,我为您提供了所需的所有最小和可执行的源代码(即使有"很多"文件,每个文件都经过了最小化,并且只包含严格的最小行,以便您能够重现错误)。在创建了相应的文件并将这些源复制/粘贴到其中之后,运行这个最小且可执行的应用程序几次。即使每次运行都会或不会显示错误,通常在最多5次运行后,你会至少看到一次。你可以用智能手机测试这个应用程序,也可以用安卓工作室的模拟器(但我没有在模拟器上测试)。

注意:根据我给你的消息来源,你看不到文本滚动(也看不到任何文本)是完全正常的。这是因为我已经完全隔离了触发bug的API部分,滚动文本与这个错误无关,所以它不是我隔离的源代码的一部分。

我的问题

你能告诉我为什么会出现这个错误(我无法调试它),为什么它看起来如此随机吗?我该如何纠正?

最小且可执行的应用程序源

简短介绍

  1. 首先,我将向您提供库的隔离部分的来源

  2. 然后,我会给你ViewPager等应用程序的来源

  3. 即使有"很多"文件,每个文件都经过了最小化,并且只包含严格的最小行,以便能够重现错误。根据我给你的消息来源,你看不到文本滚动(也看不到任何文本)是完全正常的。这是因为我已经完全隔离了触发bug的API部分,滚动文本与这个错误无关,所以它不是我隔离的源代码的一部分。

库中触发错误的独立部分

com.example.mapplication.libs.autoscrolling_text_view.MarqueeTextView.java

package com.example.myapplication.libs.autoscrolling_text_view;
import android.content.Context;
import androidx.appcompat.widget.AppCompatTextView;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
*
* @author haohao on 2017/9/21 下午 02:33
* @version v1.0
*/
public class MarqueeTextView extends AppCompatTextView {
private int currentScrollPos = 0;
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
final TimerTask task = new TimerTask() {
@Override
public void run() {
currentScrollPos += 1;
scrollTo(currentScrollPos, 0);
}
};

public MarqueeTextView(Context context) {
super(context);
}
public void postStartScroll(int delay) {  // Bug when reset AND then scheduleAtFixedRate are executed
int speed = 6;
pool.scheduleAtFixedRate(task, delay, speed, TimeUnit.MILLISECONDS);
}
}

com.example.mapplication.libs.autocrolling_text_view.MarqueeSwitcher.java

package com.example.myapplication.libs.autoscrolling_text_view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import android.widget.ViewSwitcher;
/**
* MarqueeSwitcher {@link android.widget.TextSwitcher} t
*
* @author haohao on 2017/9/21 下午 03:57
* @version v1.0
*/
public class MarqueeSwitcher extends ViewSwitcher {
/**
* Creates a new empty TextSwitcher for the given context and with the
* specified set attributes.
*
* @param context the application environment
* @param attrs a collection of attributes
*/
public MarqueeSwitcher(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Sets the text of the next view and switches to the next view. This can
* be used to animate the old text out and animate the next text in.
*
*/
public void setText() {
final MarqueeTextView t = getNextView();
t.postStartScroll(1500);  // BUG HERE (Cf. MarqueeTextView::postStartScroll)
}
public MarqueeTextView getCurrentView() {
return (MarqueeTextView) ((RelativeLayout) super.getCurrentView()).getChildAt(0);
}
public MarqueeTextView getNextView() {
return (MarqueeTextView) ((RelativeLayout) super.getNextView()).getChildAt(0);
}
}

com.example.mapplication.libs.autoscrolling_text_view.BaseScrollTextView.java

package com.example.myapplication.libs.autoscrolling_text_view;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.ViewSwitcher;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* 父类:上下滚动
*
* @author haohao on 2017/9/21 下午 02:28
* @version v1.0
*/
public class BaseScrollTextView extends MarqueeSwitcher
implements ViewSwitcher.ViewFactory {
private static final int FLAG_START_AUTO_SCROLL = 1000;
private ArrayList<String> textList;
private Handler handler;
public BaseScrollTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
textList = new ArrayList<>();
handler = new MyHandler(this);
setFactory(this);
}
/**
* 设置数据源
*/
public void setTextList(List<String> titles) {
textList.addAll(titles);
}
/**
* 开始轮播
*/
public void startAutoScroll() {
handler.sendEmptyMessage(FLAG_START_AUTO_SCROLL);
}
@Override
public View makeView() {
RelativeLayout layout = new RelativeLayout(getContext());
MarqueeTextView textView = new MarqueeTextView(getContext());
layout.addView(textView);
return layout;
}
private static class MyHandler extends Handler {
WeakReference<BaseScrollTextView> textViewWeakReference;
private MyHandler(BaseScrollTextView autoScrollTextView) {
textViewWeakReference = new WeakReference<>(autoScrollTextView);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (null != textViewWeakReference) {
BaseScrollTextView autoScrollTextView = textViewWeakReference.get();
if (msg.what == FLAG_START_AUTO_SCROLL) {
if (autoScrollTextView.textList.size() > 0) {
autoScrollTextView.setText();
}
}
}
}
}
}

res.anim.push_up_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
android:zAdjustment="top">
<translate
android:duration="400"
android:fromYDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:toYDelta="0"/>
<alpha
android:duration="400"
android:fromAlpha="0.0"
android:toAlpha="1.0"/>
</set>

res.anim.push_up_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
android:zAdjustment="bottom">
<translate
android:duration="400"
android:fromYDelta="0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toYDelta="-100%"/>
<alpha
android:duration="400"
android:fromAlpha="1.0"
android:toAlpha="0.0"/>
</set>

应用程序(一个活动,一个片段在活动的Viewpager中使用了两次;该片段使用随机触发错误的AutoScrollTextView)

应用程序级别渐变

apply plugin: 'com.android.application'
android {
compileSdkVersion 28

defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation("com.google.guava:guava:28.2-android")
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

com.example.mapplication.MainActivity.java

package com.example.myapplication;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.common.collect.Lists;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<FragmentHomeSlide> slides;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentHomeSlide slide_1 = new FragmentHomeSlide();
final FragmentHomeSlide slide_2 = new FragmentHomeSlide();
slides = Lists.newArrayList(slide_1, slide_2);
final ViewPager view_pager = findViewById(R.id.view_pager);
assert getFragmentManager() != null;
view_pager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
@Override
@NonNull
public Fragment getItem(final int position) {
return slides.get(position);
}
@Override
public int getCount() {
return slides.size();
}
});
}
}

com.example.mapplication.FragmentHomeSlide.java

package com.example.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapplication.libs.autoscrolling_text_view.BaseScrollTextView;
import java.util.ArrayList;
import java.util.Arrays;
public class FragmentHomeSlide extends Fragment {
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
View inflated = inflater.inflate(R.layout.home_slide, container, false);
setWidgets(inflated);
return inflated;
}
private void setWidgets(View inflated) {
String[] text_presentation = new String[1];
text_presentation[0] = "Foo";
BaseScrollTextView baseScrollTextView = inflated.findViewById(R.id.main_autoscroll_text1);
baseScrollTextView.setTextList(new ArrayList<>(Arrays.asList(text_presentation)));
baseScrollTextView.startAutoScroll();
}
}

res.layout.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

res.layout.home_slide.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myapplication.libs.autoscrolling_text_view.BaseScrollTextView
android:id="@+id/main_autoscroll_text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

我想我已经通过在方法MarqueeTextView::TimerTask::run中使用runOnUiThread解决了这个问题。自从这次更改后,我没有看到任何错误。但我仍然不知道为什么会出现这个bug,以及为什么这次修改解决了它(我知道在这种情况下最好使用runOnUiThread,因为使用了scrollTo,但我不知道这个调用和bug之间的关系是什么)如果有人能评论我的回答,请解释我:-)

您可以将更改(如下所示)与我问题中的原始文件进行比较。

因此,我所做的唯一更改包含在以下文件中(com.example.myapplication.libs.autocrolling_text_view.MarkeeTextView):

package com.example.myapplication.libs.autoscrolling_text_view;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
*
* @author haohao on 2017/9/21 下午 02:33
* @version v1.0
*/
public class MarqueeTextView extends AppCompatTextView {
private int currentScrollPos = 0;
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
final TimerTask task = new TimerTask() {
@Override
public void run() {
((AppCompatActivity) getContext()).runOnUiThread(new Runnable() {
@Override
public void run() {
currentScrollPos += 1;
scrollTo(currentScrollPos, 0);
}
});
}
};
public MarqueeTextView(Context context) {
super(context);
}
public void postStartScroll(int delay) {  // Bug when reset AND then scheduleAtFixedRate are executed
int speed = 6;
pool.scheduleAtFixedRate(task, delay, speed, TimeUnit.MILLISECONDS);
}
}

相关内容

最新更新