-1

I keep getting the error but i am unable to find out how to solve it because everything seems right. Its tiring because i dont see anything wrong with my code at all. I really hope someone will help, i am very confused. I want to make a music list page, with recyclerview. I have an api as well.

Logcat:

Process: com.anisacoding.expriment, PID: 24248
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at com.anisacoding.expriment.Adapter.SoundAdapter.getItemCount(SoundAdapter.java:58)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:4044)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3849)
    at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
    at android.view.View.layout(View.java:22419)
    at android.view.ViewGroup.layout(ViewGroup.java:6584)
    at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1762)
    at android.view.View.layout(View.java:22419)
    at android.view.ViewGroup.layout(ViewGroup.java:6584)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:22419)
    at android.view.ViewGroup.layout(ViewGroup.java:6584)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
    at android.view.View.layout(View.java:22419)
    at android.view.ViewGroup.layout(ViewGroup.java:6584)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:22419)
    at android.view.ViewGroup.layout(ViewGroup.java:6584)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
    at android.view.View.layout(View.java:22419)
    at android.view.ViewGroup.layout(ViewGroup.java:6584)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:1041)
    at android.view.View.layout(View.java:22419)
    at android.view.ViewGroup.layout(ViewGroup.java:6584)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3378)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2842)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1888)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8511)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
    at android.view.Choreographer.doCallbacks(Choreographer.java:761)
    at android.view.Choreographer.doFrame(Choreographer.java:696)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7050)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

ApiInterface:

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    /////getting all posts/////
    @GET("posts.php")
    Call<Users> performAllPosts();

    ///////getting all sounds//////

    @GET("sounds.php")
    Call<Users> performAllSounds();

}

ApIClient:

    import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BASE_URL = "http://www.rojkharido.com/tiktok/";
    public static Retrofit retrofit = null;
    public static Retrofit getApiClient() {
        if(retrofit ==null){
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();

        }
        return retrofit;
    }
}

Users:

import com.anisacoding.expriment.Model.MediaObject;
import com.anisacoding.expriment.Model.SoundModel;
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

public class Users {

    @SerializedName("ALL_POSTS")
    private ArrayList<MediaObject> AllPosts;

    @SerializedName("All_SOUNDS")
    private ArrayList<SoundModel> AllSounds;


        public ArrayList<MediaObject> getAllPosts(){
        return AllPosts;
    }

    public ArrayList<SoundModel> getAllSounds(){
            return AllSounds;
    }
}

SoundModel:

public class SoundModel {
    
    public SoundModel ()
    {
        //////////////////
    }
    private String  sound_id, sound_title, sound_image, sound_file;

    public SoundModel( String sound_id, String sound_title, String sound_image, String sound_file) {
        this.sound_id = sound_id;
        this.sound_image = sound_image;
        this.sound_title = sound_title;
        this.sound_file = sound_file;
    }

    public String getSound_id() {
        return sound_id;
    }

    public void setSound_id(String sound_id) {
        this.sound_id = sound_id;
    }

    public String getSound_title() {
        return sound_title;
    }

    public void setSound_title(String sound_title) {
        this.sound_title = sound_title;
    }


    public String getSound_image() {
        return sound_image;
    }

    public void setSound_image(String sound_image) {
        this.sound_image = sound_image;
    }

    public String getSound_file() {
        return sound_file;
    }

    public void setSound_file(String sound_file) {
        this.sound_file = sound_file;
    }
}

SoundActivity:

 private RecyclerView recyclerview;
    private List<SoundModel> soundModelList = new ArrayList<>();
    private SoundAdapter soundAdapter;
    public static ApiInterface apiInterface;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sound);

        apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(this);
        layoutManager3.setOrientation(RecyclerView.VERTICAL);
        recyclerview.setLayoutManager(new GridLayoutManager(this, 2));

      Call<Users> call = apiInterface.performAllSounds();
      call.enqueue(new Callback<Users>() {
          @Override
          public void onResponse(Call<Users> call, Response<Users> response) {
              if (response.isSuccessful())
              {
                  soundModelList = response.body().getAllSounds();
                  soundAdapter = new SoundAdapter(soundModelList, getApplicationContext());
                  recyclerview.setAdapter(soundAdapter);
                  soundAdapter.notifyDataSetChanged();
              } else{
                  Toast.makeText(SoundActivity.this, "network error", Toast.LENGTH_SHORT).show();
              }
          }

          @Override
          public void onFailure(Call<Users> call, Throwable t) {
              Toast.makeText(SoundActivity.this, "network error", Toast.LENGTH_SHORT).show();

          }
      });    

    }
        public void backBtn (View view){
            Intent intent = new Intent(SoundActivity.this, PortraitCameraActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            Animatoo.animateInAndOut(this);
            finish();
        }


        @Override
        public void onBackPressed () {
            Intent intent = new Intent(SoundActivity.this, PortraitCameraActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            Animatoo.animateInAndOut(this);
            finish();
        }

    }

SoundAdapter:

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.anisacoding.expriment.Model.SoundModel;
import com.anisacoding.expriment.R;
import com.anisacoding.expriment.VideoEditorFolder.PortraitCameraActivity;

import java.util.List;


public class SoundAdapter extends RecyclerView.Adapter<SoundAdapter.SoundViewHolder> {
    List<SoundModel> soundModelList;
    Context context;

    public SoundAdapter(List<SoundModel> soundModelList, Context context) {
        this.soundModelList = soundModelList;
        this.context = context;
    }

    @NonNull
    @Override
    public SoundViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_sound, viewGroup, false);
        return new SoundViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull SoundViewHolder holder, int position) {

        SoundModel soundModel = soundModelList.get(position);
        holder.sound_title.setText(soundModel.getSound_title());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, PortraitCameraActivity.class);
                intent.putExtra("sound_url", soundModel.getSound_file());
                intent.putExtra("sound_title", soundModel.getSound_title());
                context.startActivity(intent);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            }
        });

    }

    @Override
    public int getItemCount() {
        return soundModelList.size();
    }


    public class SoundViewHolder extends RecyclerView.ViewHolder {

        private TextView sound_title;

        public SoundViewHolder(@NonNull View itemView) {
            super(itemView);

            sound_title = itemView.findViewById(R.id.music_title);
        }
    }
}

Layout:

<?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="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">


    <ImageView
        android:id="@+id/imageView20"
        android:layout_width="157dp"
        android:layout_height="141dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:contentDescription="@string/library_music"
        app:tint="#000000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_library_music" />

    <TextView
        android:id="@+id/music_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:maxLength="50"
        android:text="Alaf file song ......."
        android:textColor="@android:color/white"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/imageView20"
        app:layout_constraintStart_toStartOf="@+id/imageView20"
        app:layout_constraintTop_toBottomOf="@+id/imageView20"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/white"
    tools:context=".Activities.SoundActivity">

    <ImageView
        android:id="@+id/cross"
        android:layout_width="43dp"
        android:layout_height="43dp"
        android:layout_marginTop="4dp"
        android:contentDescription="@string/cross"
        android:onClick="backBtn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_cross" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="408dp"
        android:layout_height="730dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • Is there a reason why `@SerializedName("ALL_POSTS")` is with all capitals, but `@SerializedName("All_SOUNDS")` is with lowercase `l` instead of `L` in the word 'all'? The NullPointerException you get is because the `AllSounds`-list is `null`. So the serialization fails, which I assume has something to do with those lowercase letters. I'm not too familiar with how the `@SerializedName` annotations of `com.google.gson.annotations` work though, so perhaps I'm mistaken. – Kevin Cruijssen Sep 17 '20 at 12:08
  • I love you so much ❤️ , it worked. – Anisa Mohamed Sep 17 '20 at 12:29

1 Answers1

0

The error says by itself:

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at com.anisacoding.expriment.Adapter.SoundAdapter.getItemCount(SoundAdapter.java:58)

So you should look at your SoundAdapter.getItemCount, where you are getting a NPE when using the List.size() there. Just make sure you initialize your list in this case! =)

Dharman
  • 30,962
  • 25
  • 85
  • 135
Lucas Campos
  • 1,860
  • 11
  • 17