0

im new to android development and i have managed to develop an application with a listview of name, phone number and district, which is searchable and it is working really well. im using positions to click and take me to the dial pad, but the problem is, if an item is searched, it does not mantain its position given to it initially. what i want when a user searches for a name or district, it opens in the dial pad with a number written there. Here is my contacts.java

public class Contacts extends AppCompatActivity {
    ListView listView;
    String[] name = {"Achibu john peter - Serere - 0772698033", "Agaba - Amon - Rukiga - 
     0782090694\n", "Agaja joseph - kaberamaido - 0775004193/0752451894\n",}
     ArrayAdapter<String> arrayAdapter;

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("DFO Contacts");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        listView = findViewById(R.id.listview);


        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0){
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                      intent.setData(Uri.parse("tel: +256772698033"));
                      startActivity(intent);
                }
            }
        });


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView) menuItem.getActionView();
        searchView.setQueryHint("Search for your DFO");

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                arrayAdapter.getFilter().filter(newText);
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
            

and menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/search_view"
        android:title="Search"
        app:showAsAction="always"
        android:icon="@drawable/ic_search"
        app:actionViewClass="android.widget.SearchView"

        />
</menu>

And the activity_contacts

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".Contacts">



    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#D4AC0D"
        app:subtitleTextColor="#0A0A0A"
        app:titleTextColor="#111111"
         />

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fontFamily="@font/poppinsmedium"
        android:textSize="20sp"
        android:layout_marginLeft="15dp"
        android:clickable="true"
        />


</LinearLayout>
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Does this answer your question? [Is there a way to get the source code from an APK file?](https://stackoverflow.com/questions/3593420/is-there-a-way-to-get-the-source-code-from-an-apk-file) – gutyina70 Jun 02 '22 at 09:23
  • No @Federico, all i want is that when you click on any seachable item, it takes you to the dial pad, without using positions – Iradukunda Reyanne Jun 02 '22 at 09:30
  • @IradukundaReyanne you need to use filterable in your adapter while search, so that it will give proper arraylist with positions. – Bhoomika Patel Jun 02 '22 at 09:37
  • please show me an example using the contacts java i have provided, thankyou @BhoomikaPatel – Iradukunda Reyanne Jun 02 '22 at 10:04
  • @IradukundaReyanne "no" what? I didn't ask anything, I just reformatted your question. – Federico klez Culloca Jun 02 '22 at 10:17
  • @IradukundaReyanne check this answer, and customize your adapter. https://stackoverflow.com/a/20743661/6534707 – Bhoomika Patel Jun 02 '22 at 10:34
  • searching is fine, it works perfectly well, but i want it to search and on click of the searched item you go to the dail pad of the phone, each list item to have its own dial pad – Iradukunda Reyanne Jun 02 '22 at 10:53
  • @IradukundaReyanne, You need to use custom ```Array Adapter``` with custom ```Layout``` with a ```TextView``` and add ```OnClickListener``` for each ```TextView```. – Gouranga Das Jun 03 '22 at 15:58

1 Answers1

0

You need to use custom Array Adapter with custom Layout with a TextView and add OnClickListener for each TextView.

I've changed your code to make it work.

contacts.java

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SearchView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class Contacts extends AppCompatActivity {

    ListView listView;
    List<String> name;
    CustomAdapter arrayAdapter;

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

        // Set Toolbar & title
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("DFO Contacts");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        listView = findViewById(R.id.listview);

        // Creating List<String> from valus
        name = new ArrayList<>();
        name.add("Achibu john peter - Serere - 0772698033");
        name.add("Agaba - Amon - Rukiga - 0782090694");
        name.add("Agaja joseph - kaberamaido - 0775004193");
        arrayAdapter = new CustomAdapter(name, this);
        listView.setAdapter(arrayAdapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        MenuItem menuItem = menu.findItem(R.id.search_view);

        SearchView searchView = (SearchView) menuItem.getActionView();
        searchView.setQueryHint("Search for your DFO");

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                arrayAdapter.getFilter().filter(newText);
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);

    }
}

CustomAdapter.java

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;

public class CustomAdapter  extends ArrayAdapter<String> {

    private final LayoutInflater mInflater;
    private final int mResource;
    private Context mContext;
    private List<String> orig;
    private List<String> dataSet;
    private int selectedPosition;

    public CustomAdapter(List<String> data, Context context) {
        super(context, android.R.layout.simple_list_item_1, data);

        mContext = context;

        // We need to make backup of original list

        dataSet = data;
        orig = data;

        // Store for later use

        mInflater = LayoutInflater.from(context);
        mResource = android.R.layout.simple_list_item_1;

    }


    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        return createItemView(position, convertView, parent);
    }

    private View createItemView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            convertView = mInflater.inflate(mResource, parent, false);
            viewHolder.txtName = convertView.findViewById(android.R.id.text1);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        String item = getItem(position);
        viewHolder.txtName.setText(item);

        // Here we will try to extract phone number from current item
        // it looks like    xxxxx - xxxxx - 1234567890
        // or like          xxxxx - xxxxx -xxxxxx - 1234567890
        // we need to extract 1234567890 here
        // we will split by "-" & last one in array will be the phone number
        // you may try another way to get so

        String[] s = item.split("-");
        String p = s[s.length-1].trim();    // Extracted Phone Number

        viewHolder.txtName.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel: " + p));
            mContext.startActivity(intent);
        });

        return convertView;
    }


    // View lookup cache
    private static class ViewHolder {
        TextView txtName;
    }

    public Filter getFilter() {
        return new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<String> results = new ArrayList<String>();
                if (orig == null)
                    orig = dataSet;
                if (constraint != null) {
                    if (orig != null && orig.size() > 0) {
                        for (final String g : orig) {
                            if (g.toLowerCase()
                                    .contains(constraint.toString()))
                                results.add(g);
                        }
                    }
                    oReturn.values = results;
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                dataSet = (List<String>) results.values;
                notifyDataSetChanged();
            }
        };
    }

    @Override
    public int getCount() {
        return dataSet.size();
    }

    @Override
    public String getItem(int position) {
        return dataSet.get(position);
    }

}

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search_view"
        android:icon="?android:attr/actionModeWebSearchDrawable"
        android:title="Search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="always" />
</menu>

and activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="15dp"
        android:clickable="true"
        android:textSize="20sp"
        tools:listitem="@android:layout/simple_list_item_1"
        android:focusable="true" />

</LinearLayout>

Hope it will help.

Gouranga Das
  • 374
  • 3
  • 10
  • can i have a look at the xml you are using because, when i put this code in my app, the application just crushes the moment i click on the button to take me to that activity – Iradukunda Reyanne Jun 06 '22 at 08:28
  • this has not helped at all, the app just crushes – Iradukunda Reyanne Jun 06 '22 at 12:08
  • @Iradukunda Reyanne I have used the same **menu.xml** & **activity_contacts.xml** that you have attached in your question. Which type issue did you faced? Can you please pass the logcat so that I can look into. – Gouranga Das Jun 06 '22 at 14:01
  • i created a whole new app but still it crushes before opening, here is the error i get. Process: com.example.onclocklistenerwithclick, PID: 6334 java.lang.ClassCastException: android.widget.SearchView cannot be cast to androidx.appcompat.widget.SearchView at com.example.onclocklistenerwithclick.MainActivity.onCreateOptionsMenu(MainActivity.java:45) – Iradukunda Reyanne Jun 08 '22 at 07:58
  • I can understand that `android.widget.SearchView` is used in `menu.xml` but `import androidx.appcompat.widget.SearchView` is used instead of `import android.widget.SearchView` in `MainActivity.java`. Thus `java.lang.ClassCastException` has been occured. Solution : Replace `import androidx.appcompat.widget.SearchView;` with `import android.widget.SearchView;` in `MainActivity.java`. – Gouranga Das Jun 08 '22 at 09:44
  • @Iradukunda Reyanne, I have changed my post to make more easier to understand. Hope it will solve your issue. – Gouranga Das Jun 08 '22 at 09:56
  • thank you @Gouranga, it can now open, but searching, it brings Achibu john peter even if you are searching for Agaba, so the search is not working. and another thing how do i make it in a way that when i click on any name, it brings its phone number and not the one of Achibu john peter. thank you – Iradukunda Reyanne Jun 08 '22 at 10:33
  • @Iradukunda Reyanne, Please check my updated post totally. Hope it will solve your issue. If anything wrong you face, please let me know. – Gouranga Das Jun 08 '22 at 12:30
  • i really appreciate your commitment to make this work, thank you very much, it now works like the way i wanted, you have not saved only me, but i believe there others who had the same issue. thumbs up – Iradukunda Reyanne Jun 10 '22 at 08:09