Search code examples
androidandroid-activity

Android listview adapter check if it contains a string


Hello i am kind of new to programming in android so far day by day am managing to learn something new but at times i do get stuck , today i am working on a simple project with listview and a button to check if it contains a specific string in the listview.

here is my code

private ListView listView1 ;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blockcontact);
        listView1 = (ListView) findViewById( R.id.listView1 );
        Button button6 = (Button) findViewById(R.id.button6);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
        list.add("07474715336");
        list.add("+61470405818");
        list.add("470105848");
        button6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = getApplicationContext();
                String strName = "+61470405818";
                for (int i = 0; i < listView1.getAdapter().getCount(); i++) {
                    if (strName.equals(list)) {

                        CharSequence text = "found";
                        int duration = Toast.LENGTH_SHORT;

                        Toast toast = Toast.makeText(context, text, duration);
                        toast.show();

                    } else

                        context = getApplicationContext();
                    CharSequence text = "not found";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    {


                    }
                }
            }
        });

 listView1.setAdapter(adapter);

am trying to check if this number exist String strName = "+61470405818";

the list may contain large numbers so i want to first loop through the list and then check using index if the item exist or not.


Solution

  • You should compare the items inside the list with your target String.

    So instead of:

    strName.equals(list);
    

    use:

    strName.equals((String)listView1.getAdapter().getItem(i));