[英]Null Pointer Exception with Fragment - Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)'
[英]Encountering a Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
我正在做一个制作音乐流媒体应用程序的学校项目。 我决定在前面的屏幕上使用回收器视图显示歌曲。 但是,当我运行该应用程序时,我收到此错误并且该应用程序立即崩溃。 如果有人可以帮助我,我将不胜感激。 谢谢
错误日志:
Process: com.example.musicstream, PID: 1641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musicstream/com.example.decibel.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3792)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at com.example.decibel.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:8198)
at android.app.Activity.performCreate(Activity.java:8182)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3765)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
主要活动:
package com.example.decibel;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.example.decibel.R;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
SongCollection songCollection = new SongCollection();
List<Song> songList = songCollection.getSongList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.oneSongLayout);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new RecycleViewAdapter(songList, MainActivity.this);
recyclerView.setAdapter(mAdapter);
}
public void sendDataToActivity (int index){
Intent intent = new Intent(this, PlaySongActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
public void handleSelection(View myView){
String resourceId = getResources().getResourceEntryName(myView.getId()); //myView.getId() returns int that android makes for the ImgBtn, the rest of ir helps discover the String ID,(S1001, S1002)
int currentArrayIndex = songCollection.searchSongById(resourceId);
Log.d("temasek", "The id of the pressed ImageButton is: " + resourceId);
sendDataToActivity(currentArrayIndex);
}
}
RecyclerViewAdapter:
package com.example.decibel;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Text;
import java.util.List;
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> {
List<Song> songList;
Context context;
public RecycleViewAdapter(List<Song> songList, Context context) {
this.songList = songList;
this.context = context;
}
@NonNull
@NotNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one_song,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull @NotNull RecycleViewAdapter.MyViewHolder holder, int position) {
holder.songName.setText(songList.get(position).getTitle());
holder.artistName.setText(songList.get(position).getArtist());
Picasso.get().load(songList.get(position).getCoverArt()).into(holder.coverArt);
}
@Override
public int getItemCount() {
return songList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView coverArt;
TextView songName;
TextView artistName;
public MyViewHolder(@NonNull @org.jetbrains.annotations.NotNull View itemView) {
super(itemView);
coverArt = itemView.findViewById(R.id.coverArt);
songName = itemView.findViewById(R.id.songName);
artistName = itemView.findViewById(R.id.artistName);
}
}
}
歌曲合集:
package com.example.decibel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SongCollection {
List<Song> songList = new ArrayList<Song>();
private Song songs[] = new Song[25];
public SongCollection(){
Song theWayYouLookTonight = new Song(
"S1001",
"The Way You Look Tonight",
"Michael Bublé",
"pop",
"https://p.scdn.co/mp3-preview/a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=2afe87a64b0042dabf51f37318616965",
"https://cdns-images.dzcdn.net/images/cover/a5dd92ae1b53ad19f39e3036dd510541/500x500-000000-80-0-0.jpg",
4.66);
Song billieJean = new Song(
"S1002",
"Billie Jean",
"Michael Jackson",
"pop",
"https://p.scdn.co/mp3-preview/14a1ddedf05a15ad0ac11ce28b40ea1a15fabd20?cid=2afe87a64b0042dabf51f37318616965",
"https://cdns-images.dzcdn.net/images/cover/ebeac32e9207c60877228ddc5bb37233/500x500-000000-80-0-0.jpg",
4.9);
Song dreamyNight = new Song(
"S1003",
"dreamy night",
"LilyPichu",
"lofi",
"https://p.scdn.co/mp3-preview/9956e838630df9a0dfdb3753ad38ef1fc7cee5e7?cid=2afe87a64b0042dabf51f37318616965",
"https://cdns-images.dzcdn.net/images/cover/6b2f8b3ff0e6cd136e685afa2940fcba/500x500-000000-80-0-0.jpg",
4.1 );
songs[0] = theWayYouLookTonight;
songs[1] = billieJean;
songs[2] = dreamyNight;
songList.addAll(Arrays.asList());
}
public List<Song> getSongList() {
return songList;
}
public Song getCurrentSong(int currentSongId){
return songs[currentSongId];
}
//Finds song which has the same id and returns its position the the songs array
public int searchSongById(String id){
for (int index=0; index < songs.length; index++){
Song tempSong = songs[index];
if(tempSong.getId().equals(id)){
return index;
}
}
return -1;
}
public int getNextSong(int currentSongIndex) {
if (currentSongIndex >= songs.length-1){
return currentSongIndex;
}
else{
return currentSongIndex + 1;
}
}
public int getPrevSong(int currentSongIndex) {
if (currentSongIndex <= 0){
return currentSongIndex;
}
else{
return currentSongIndex - 1;
}
}
}
回收商 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="com.example.decibel.MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/songList"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
布局 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"
android:id="@+id/oneSongLayout">
<ImageView
android:id="@+id/coverArt"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/home1" />
<TextView
android:id="@+id/songName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
android:text="TextView"
android:textAlignment="textStart"
android:textSize="16sp"
app:layout_constraintStart_toEndOf="@+id/coverArt"
app:layout_constraintTop_toTopOf="@+id/coverArt" />
<TextView
android:id="@+id/artistName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
android:text="TextView"
android:textSize="12sp"
app:layout_constraintStart_toEndOf="@+id/coverArt"
app:layout_constraintTop_toBottomOf="@+id/songName" />
</androidx.constraintlayout.widget.ConstraintLayout>
抱歉,如果问题不是很合适,我对 Android 中的编码很陌生
在您的布局中,回收器的 ID @+id/songList
,但在代码中,您正在执行findViewById(R.id.oneSongLayout)
。 oneSongLayout
在布局中是不存在的,所以recyclerview是null。
将行更改为:
recyclerView = findViewById(R.id.songList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.