2

I am working with java inside of android studio. I am needing to filter a list of charities by their category when the radio button is chosen. Example: Click Medical radio button and it gives a list of charities that their category is medical. What is the best way to do this? It would be nice if there is a very compact way to do this, but as long as it works I am fine with that. Below is my code for main activity and my object w/ setters and getters.

Main:

package com.example.charityfinder;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //references to buttons and other controls

    Button submitbtn;
    RadioButton medicalRadio, envirRadio, hserviceRadio, educationRadio, publicaRadio,
            cultureRadio, domesticvRadio, hrightsRadio, homelessRadio, religionRadio, youthRadio;


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

        readcharitydata();
        filterCharity();


        medicalRadio = findViewById(R.id.medicalRadio);
        envirRadio = findViewById(R.id.envirRadio);
        hserviceRadio = findViewById(R.id.hserviceRadio);
        educationRadio = findViewById(R.id.educationRadio);
        publicaRadio = findViewById(R.id.publicaRadio);
        cultureRadio = findViewById(R.id.cultureRadio);
        domesticvRadio = findViewById(R.id.domesticvRadio);
        hrightsRadio = findViewById(R.id.hrightsRadio);
        homelessRadio = findViewById(R.id.homelessRadio);
        religionRadio = findViewById(R.id.religionRadio);
        youthRadio = findViewById(R.id.youthRadio);
        submitbtn = findViewById(R.id.submitbtn);
        submitbtn.setOnClickListener(new View.OnClickListener() {
            String category;
            @Override
            public void onClick(View view) {

                if (medicalRadio.isChecked()) {
                    category = "Medical";
                } else if (envirRadio.isChecked()) {
                    category = "Environmental_Animal";
                } else if (hserviceRadio.isChecked()) {
                    category = "Human_Services";
                } else if (educationRadio.isChecked()) {
                    category = "Education";
                } else if (publicaRadio.isChecked()) {
                    category = "Public_Affairs";
                } else if (cultureRadio.isChecked()) {
                    category = "Culture_Arts_Humanities";
                } else if (domesticvRadio.isChecked()) {
                    category = "Domestic_Violence";
                } else if (hrightsRadio.isChecked()) {
                    category = "Human_Rights";
                } else if (homelessRadio.isChecked()) {
                    category = "Homelessness";
                } else if (religionRadio.isChecked()) {
                    category = "Religious";
                } else if (youthRadio.isChecked()) {
                    category = "Youth";
                }

                filterCharity(category);
            }

        });

    }

    private List<NationalCharity> charities = new ArrayList<>();

    private void readcharitydata() {
        InputStream is = getResources().openRawResource(R.raw.charities);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

        String line = "";
        try {
            //ignore headers
            reader.readLine();
            while ((line = reader.readLine()) != null) {
                //split by comma
                String[] token = line.split(",");
                //Read data
                NationalCharity charity = new NationalCharity();
                charity.setCharity_name(token[0]);
                charity.setCategory(token[1]);
                charity.setWeb_address(token[2]);
                charity.setAddress(token[3]);
                charity.setCity(token[4]);
                charity.setState(token[5]);
                charity.setZipcode(token[6]);
                charity.setMission_statement(token[7]);
                charities.add(charity);

                Log.d("Debug", "Just created: " + charity);
            }
        } catch (IOException e) {
            Log.wtf("Error", "Error reading data file" + line, e);
            e.printStackTrace();
        }

    }

    //needing to filter here from the charities list
    private void filterCharity(String type) {
        if(type.equals("Medical")) {}
        else if(type.equals("Environmental_Animal")) {}
        else if(type.equals("Human_Services")) {}
        else if(type.equals("Education")) {}
        else if(type.equals("Public_Affairs")) {}
        else if(type.equals("Culture_Arts_Humanities")) {}
        else if(type.equals("Domestic_Violence")) {}
        else if(type.equals("Human_Rights")) {}
        else if(type.equals("Homelessness")) {}
        else if(type.equals("Religious")) {}
        else if(type.equals("Youth")) {}


    }

     /*Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
        intent.putExtra("Category", results);
        Log.d("DEBUG: ", results);
        startActivity(intent);*/
}

Object:

package com.example.charityfinder;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import org.bson.types.ObjectId;


public class NationalCharity extends RealmObject {
    @PrimaryKey
    private ObjectId _id;

    private String Address;

    private String Category;

    private String Charity_name;

    private String City;

    private String Mission_statement;

    private String State;

    private String Web_address;

    private String Zipcode;

    public NationalCharity() {}

    // Standard getters & setters
    public ObjectId get_id() { return _id; }
    public void set_id(ObjectId _id) { this._id = _id; }

    public String getAddress() { return Address; }
    public void setAddress(String Address) { this.Address = Address; }

    public String getCategory() { return Category; }
    public void setCategory(String Category) { this.Category = Category; }

    public String getCharity_name() { return Charity_name; }
    public void setCharity_name(String Charity_name) { this.Charity_name = Charity_name; }

    public String getCity() { return City; }
    public void setCity(String City) { this.City = City; }

    public String getMission_statement() { return Mission_statement; }
    public void setMission_statement(String Mission_statement) { this.Mission_statement = Mission_statement; }

    public String getState() { return State; }
    public void setState(String State) { this.State = State; }

    public String getWeb_address() { return Web_address; }
    public void setWeb_address(String Web_address) { this.Web_address = Web_address; }

    public String getZipcode() { return Zipcode; }
    public void setZipcode(String Zipcode) { this.Zipcode = Zipcode; }

    @Override
    public String toString() {
        return "Charity name: " + getCharity_name() + " " + "Category: " + getCategory() + "\n" +
                "Address: " + getAddress() + " " + "City: " + getCity() + " " + "State: " + getState() + " " +
                "Zip code: " + getZipcode() + "\n" + "Mission Statement: " + getMission_statement() + "\n" +
                "Web Address: " + getWeb_address() + "\n";
    }
}
3
  • Check this: stackoverflow.com/questions/16063338/… Commented Apr 8, 2022 at 16:19
  • NOT RELATED: Please note the following points: 1. Use view binding instead of findViewById() that's a lot better. 2. Use switch statement where the value is defined ie you what it is. Commented Apr 8, 2022 at 16:51
  • NOT RELATED: Instead of using hard-coded values, make a class and use them as public static variables. This prevents some error while doing the .equals() task Commented Apr 8, 2022 at 16:59

2 Answers 2

3

You can use Stream.filter():

charities.stream().filter(c -> type.equals(c.getCharity_name());
Sign up to request clarification or add additional context in comments.

2 Comments

1 drawback of your answer according to what I felt and tested. This method takes longer as compared to mine is the list is small. 1 Advantage of your answer that it is better than my answer when compared with large lists
I would not sacrifice code readability for performance, which depends entirely on the context
0

You can try this to filter:

 private void filterCharity(String type) {
    List<NationalCharity> filteredList = new ArrayList<>();
    for(NationalCharity charityData : charities)
        if(charityData.getCharity_name().equalsIgnoreCase(type)) 
            filteredList.add(charityData);
    // you have the filtered list "filteredList". Use it however you want
 }

Comments

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.