2

How do I remove all null and empty string values from an object in JSON java android from retrofit?

Filter out any items where "name" is blank or null.

this is my Main Activity

   Api api = retrofit.create(Api.class);
    Call<List<MainData>> call = api.getData();
    call.enqueue(new Callback<List<MainData>>() {
        @Override
        public void onResponse (Call<List<MainData>> call, Response<List<MainData>> response) {
            if (!response.isSuccessful()) {
                Toast.makeText(MainActivity.this, response.code(), Toast.LENGTH_SHORT).show();
                return;
            }
            List<MainData> postList = response.body();





            // Filter out any items where "name" is blank or null.
            List<MainData> tempList = new ArrayList<>();
            for(MainData data :postList)
            {

                if(null!= data.getName() && !data.getName().isEmpty()) {

                     //sort by name
                    Collections.sort(tempList, (mainData, t1) -> mainData.getName().compareTo(t1.getName()));

                   //sort by ListId
                    Collections.sort(tempList, (mainData, t1) -> mainData.getListId().compareTo(t1.getListId()) );

                    tempList.add(data);


                }

            }


            RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(tempList, MainActivity.this);
            recyclerView.setAdapter(recyclerViewAdapter);
        }

        @Override
        public void onFailure (Call<List<MainData>> call, Throwable t) {
            Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

This Is My Adpater

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
//initialize variables

List<MainData> dataArrayList;
Context context;
//create constructor

public RecyclerViewAdapter (Context context, List<MainData> dataArrayList) {
    this.dataArrayList = dataArrayList;
    this.context = context;
}
    
@NonNull
@Override
public ViewHolder onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
    //this method recycling the view holder
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_item, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder (@NonNull ViewHolder holder, int position) {
    //initialize Main data
    MainData data = dataArrayList.get(position);
    //set name on text view
    holder.listId.setText(String.format("list_id : %s", data.getListId()));
    holder.name.setText(String.format("name : %s", data.getName()));
    holder.id.setText(String.format("id : %s", data.getId()));
}

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


public class ViewHolder extends RecyclerView.ViewHolder {
    //initialize variables


    TextView listId, name, id;

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

        //assign variables


        listId = itemView.findViewById(R.id.list_id);
        name = itemView.findViewById(R.id.name);
        id = itemView.findViewById(R.id.id);

    }

}

}

this is the Data

public class MainData {

public String listId, name, id;



public String getListId () {
    return listId;
}

public  String getName () {
    return name;
}

public  String getId () {
    return id;
}

}

And this is the Api

public interface Api {

@GET("hiring.json")
Call<List<MainData>> getData();

}

And this is my app I want to remove nulls and emp enter image description here

1 Answer 1

3

There are two ways

(1) While inflating the data you can filter these unwanted values (2) Create a temporary list and add only required values from the main list. sample code:

List<MainData> tempList = new ArrayList<>();
    for(MainData data :postList)
    {
      if(null!= data.getName() && !data.getName().isEmpty())
       {   tempList.add(data);

        }
    }

And then pass this tempList to the adapter.

Final code would look like this.

 Api api = retrofit.create(Api.class);
Call<List<MainData>> call = api.getData();
call.enqueue(new Callback<List<MainData>>() {
    @Override
    public void onResponse (Call<List<MainData>> call, Response<List<MainData>> response) {
        if (!response.isSuccessful()) {
            Toast.makeText(MainActivity.this, response.code(), Toast.LENGTH_SHORT).show();
            return;
        }
        List<MainData> postList = response.body();

        //sort by ListId
        Collections.sort(postList, (mainData, t1) -> mainData.getListId().compareTo(t1.getListId()));

        // Filter out any items where "name" is blank or null.
      List<MainData> tempList = new ArrayList<>();
    for(MainData data :postList)
    {
      if(null!= data.getName() && !data.getName().isEmpty())
       {   tempList.add(data);

        }
    }
        

        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(MainActivity.this, tempList );
        recyclerView.setAdapter(recyclerViewAdapter);
    }

    @Override
    public void onFailure (Call<List<MainData>> call, Throwable t) {
        Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

}

Feel free to ask if something is unclear.

Sign up to request clarification or add additional context in comments.

6 Comments

bro when i add tempList to the adapter the , the postlist in the top adapter is becoming red and saying Cannot resolve symbol 'postList'
like this: error: cannot find symbol adapter = new RecyclerViewAdapter(MainActivity.this, postList, dataArrayList); ^ symbol: variable postList location: class MainActivity
Hey, I have updated the answer, try it. I just added the filter code in your previous code at the appropriate place.
brother thank you so much, I really cried 😭 bro , I was struggling this for three days no stop coding and failing. thank you so much I really want to hug you bro
do you have Instagram i want to follow you, thank you bro
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.