加载时 Android RecyclerView 崩溃

时间:2021-06-29 15:25:19

标签: android android-studio android-layout android-fragments android-recyclerview

我正在尝试使用通过 recyclerview 实现的应用程序抽屉创建一个 andorid 启动器 - 基本上我只想拥有设备上所有已安装应用程序的列表。

目前,当我运行活动时它崩溃了,我不太确定为什么。错误字符串指向我的 AppDrawer.java 中的 第 23 行,但我不确定有什么问题

这是持有 recyclerview 的 Activity,AppDrawer.java

public class AppDrawer extends AppCompatActivity {


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

        recyclerView = findViewById(R.id.appsList);

        AppAdapter adapter = new AppAdapter(this);
        adapter.onCreateViewHolder(recyclerView, 0);        // LINE 23
    }
}

app_drawer.xml

<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=".AppDrawer">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/appsList"/>                   //RECYCLERVIEW ID

</androidx.constraintlayout.widget.ConstraintLayout>

这是AppAdapter.java

public class AppAdapter extends RecyclerView.Adapter<AppAdapter.ViewHolder> {
    private List<AppObject> appsList;

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView textView;
        public ImageView img;

        //This is the subclass ViewHolder which simply
        //'holds the views' for us to show on each row
        public ViewHolder(View itemView) {
            super(itemView);

            //Finds the views from our row.xml
            textView = (TextView) itemView.findViewById(R.id.text);
            img = (ImageView) itemView.findViewById(R.id.image);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick (View v) {
            int pos = getAdapterPosition();
            Context context = v.getContext();

            Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(appsList.get(pos).getName());
            context.startActivity(launchIntent);
            Toast.makeText(v.getContext(), appsList.get(pos).getName(), Toast.LENGTH_LONG).show();

        }
    }



    public AppAdapter(Context c) {

        //This is where we build our list of app details, using the app
        //object we created to store the label, package name and icon

        PackageManager pm = c.getPackageManager();
        appsList = new ArrayList<AppObject>();

        Intent i = new Intent(Intent.ACTION_MAIN, null);
        i.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> allApps = pm.queryIntentActivities(i, 0);
        for(ResolveInfo ri:allApps) {
            AppObject app = new AppObject(ri.loadLabel(pm).toString(), ri.activityInfo.packageName, ri.activityInfo.loadIcon(pm), false);
//            app.getName() = ri.loadLabel(pm);
//            app.getPackageName() = ri.activityInfo.packageName;
//            app.getImage() = ri.activityInfo.loadIcon(pm);
            appsList.add(app);
        }

    }

    @Override
    public void onBindViewHolder(AppAdapter.ViewHolder viewHolder, int i) {

        //Here we use the information in the list we created to define the views

        String appLabel = appsList.get(i).getName();
        String appPackage = appsList.get(i).getPackageName();
        Drawable appIcon = appsList.get(i).getImage();

        TextView textView = viewHolder.textView;
        textView.setText(appLabel);
        ImageView imageView = viewHolder.img;
        imageView.setImageDrawable(appIcon);
    }


    @Override
    public int getItemCount() {

        //This method needs to be overridden so that Androids knows how many items
        //will be making it into the list

        return appsList.size();
    }


    @Override
    public AppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        //This is what adds the code we've written in here to our target view
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        View view = inflater.inflate(R.layout.app_drawer_item, parent, false);

        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }
}

AppObject.java

public class AppObject {
    private String  name,
                    packageName;
    private Drawable image;
    private Boolean isAppInDrawer;

    public AppObject(String packageName, String name, Drawable image, Boolean isAppInDrawer) {
        this.name = name;
        this.image = image;
        this.packageName = packageName;
        this.isAppInDrawer = isAppInDrawer;
    }

    public String getPackageName() {
        return packageName;
    }
    public String getName() {
        return name;
    }
    public Drawable getImage() {
        return image;
    }
    public Boolean getIsAppInDrawer() {return isAppInDrawer;}

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setImage(Drawable image) {
        this.image = image;
    }
    public void setIsAppInDrawer(Boolean appInDrawer) {
        this.isAppInDrawer = appInDrawer;
    }
}

app_drawer_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_margin="5sp">
    <ImageView
        android:layout_width="40sp"
        android:layout_height="40sp"
        android:id="@+id/applicationIconImageView"
        android:src="@mipmap/ic_launcher"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginHorizontal="5sp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/applicationNameTextView"
            android:text="Application name"
            android:textSize="15sp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/usageTimeTextView"
            android:text="3h20m"
            android:textSize="10sp"
            android:layout_marginTop="2sp"/>
    </LinearLayout>
</LinearLayout>

这是我尝试运行代码时收到的错误消息:


06/29 18:23:14: Launching 'app' on Physical Device.
App restart successful without requiring a re-install.
$ adb shell am start -n "com.example.launcherapplication/com.example.launcherapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 7600 on device 'oneplus-oneplus_a6003-9bb351ae'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/cherapplicatio: Late-enabling -Xcheck:jni
E/cherapplicatio: Unknown bits set in runtime_flags: 0x8000
I/Perf: Connecting to perf service.
I/cherapplicatio: [GL_OOM] ClampGrowthLimit 268435456
V/Font: Change font:2
    Default family:android.graphics.Typeface@73f3fc13
E/Perf: Fail to get file list com.example.launcherapplication
    getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
E/Perf: Fail to get file list com.example.launcherapplication
    getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
V/FlingOptimizerScroller: FlingOptimizerOverScroller Init
W/cherapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
    Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
W/cherapplicatio: Accessing hidden method Landroid/graphics/FontFamily;-><init>()V (greylist, reflection, allowed)
    Accessing hidden method Landroid/graphics/FontFamily;->addFontFromAssetManager(Landroid/content/res/AssetManager;Ljava/lang/String;IZIII[Landroid/graphics/fonts/FontVariationAxis;)Z (greylist, reflection, allowed)
W/cherapplicatio: Accessing hidden method Landroid/graphics/FontFamily;->addFontFromBuffer(Ljava/nio/ByteBuffer;I[Landroid/graphics/fonts/FontVariationAxis;II)Z (greylist, reflection, allowed)
    Accessing hidden method Landroid/graphics/FontFamily;->freeze()Z (greylist, reflection, allowed)
    Accessing hidden method Landroid/graphics/FontFamily;->abortCreation()V (greylist, reflection, allowed)
    Accessing hidden method Landroid/graphics/Typeface;->createFromFamiliesWithDefault([Landroid/graphics/FontFamily;Ljava/lang/String;II)Landroid/graphics/Typeface; (greylist, reflection, allowed)
V/ViewRootImpl: The specified message queue synchronization  barrier token has not been posted or has already been removed
D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@f194ef9[MainActivity]
I/AdrenoGLES: QUALCOMM build                   : 35556ba, I9ca166462c
    Build Date                       : 08/07/19
    OpenGL ES Shader Compiler Version: EV031.27.02.00
    Local Branch                     : 
    Remote Branch                    : 
    Remote Branch                    : 
    Reconstruct Branch               : 
    Build Config                     : S P 8.0.8 AArch64
I/AdrenoGLES: PFP: 0x016ee187, ME: 0x00000000
W/Gralloc3: mapper 3.x is not supported
D/: Successfully load libgui-plugin.so, this=0x7f2fa37050
W/Choreographer: Already have a pending vsync event.  There should only be one at a time.
D/OnePlusJankManager:  Chor uploadMDM JANK_TYPE_ONCE mViewTitle = com.example.launcherapplication/com.example.launcherapplication.MainActivity--- jank level = 1
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@365f0dd
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
I/chatty: uid=10302(com.example.launcherapplication) identical 48 lines
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
I/chatty: uid=10302(com.example.launcherapplication) identical 12 lines
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
I/chatty: uid=10302(com.example.launcherapplication) identical 6 lines
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
W/cherapplicatio: resources.arsc in APK '/data/app/com.oneplus.gallery-u0eFcDkuFtHGko86_UqHPA==/base.apk' is compressed.
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
I/chatty: uid=10302(com.example.launcherapplication) identical 24 lines
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
W/cherapplicatio: resources.arsc in APK '/data/app/com.facebook.orca-omRvfq_ufIlgi54ffkzO9g==/base.apk' is compressed.
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
I/chatty: uid=10302(com.example.launcherapplication) identical 23 lines
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
I/chatty: uid=10302(com.example.launcherapplication) identical 33 lines
E/OpApplicationPackageManagerInjector: Application package com.oneplus.iconpack.square not found
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.launcherapplication, PID: 7600
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.launcherapplication/com.example.launcherapplication.AppDrawer}: android.view.InflateException: Binary XML file line #2 in com.example.launcherapplication:layout/app_drawer_item: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{ce38366 VFED..... ......I. 0,0-0,0 #7f0a0045 app:id/appsList}, adapter:null, layout:null, context:com.example.launcherapplication.AppDrawer@dd5bdd9
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3374)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: android.view.InflateException: Binary XML file line #2 in com.example.launcherapplication:layout/app_drawer_item: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{ce38366 VFED..... ......I. 0,0-0,0 #7f0a0045 app:id/appsList}, adapter:null, layout:null, context:com.example.launcherapplication.AppDrawer@dd5bdd9
     Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{ce38366 VFED..... ......I. 0,0-0,0 #7f0a0045 app:id/appsList}, adapter:null, layout:null, context:com.example.launcherapplication.AppDrawer@dd5bdd9
        at androidx.recyclerview.widget.RecyclerView.generateLayoutParams(RecyclerView.java:4514)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:669)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
        at com.example.launcherapplication.AppAdapter.onCreateViewHolder(AppAdapter.java:104)
        at com.example.launcherapplication.AppDrawer.onCreate(AppDrawer.java:23)
        at android.app.Activity.performCreate(Activity.java:7815)
        at android.app.Activity.performCreate(Activity.java:7804)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
I/Process: Sending signal. PID: 7600 SIG: 9

2 个答案:

答案 0 :(得分:0)

您的错误显示为 RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView,因此可以尝试将其添加为:

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);

答案 1 :(得分:0)

您必须为 RecyclerView 设置一个 LayoutManager。例如,对于垂直滚动列表,您应该像这样使用 LinearLayoutManager。

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

    recyclerView = findViewById(R.id.appsList);

    // add this
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    AppAdapter adapter = new AppAdapter(this);

    // replace this line by this two. (you should not call adapter method directly).
    // adapter.onCreateViewHolder(recyclerView, 0);        // LINE 23
    recyclerView.setAdapter(adapter);
    // notify the adapter that the data has changed 
    recyclerView.notifyDataSetChanged();
}