Search code examples
androidautocompletetextviewandroid-textwatcher

Add custom adapter, custom autocompletetextview and database to custom textwatcher


I'm learning Autocompetetextview to get suggestions from web service. For this I used this tutorial. The only problem in their code is They have linked their custom adapter, custom autocompletetextview and local database in the custom textwatcher using MainActivity. I do not want this as I would like to use the custom autocompletetextview in multiple classes (other than MainActivity class). So, I would like to know if I can get these 3 things without using MainActivity as an object.

public class MainActivity extends AppCompatActivity {

    CustomAutoCompleteView myAutoComplete;

    // adapter for auto-complete
    ArrayAdapter<MyObject> myAdapter;

    // for database operations
    DatabaseHandler databaseH;
    private static final String LOCATION = "http://example.com/android/location";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try{

            // instantiate database handler
            databaseH = new DatabaseHandler(MainActivity.this);

            // put sample data to database
            insertSampleData();

            // autocompletetextview is in activity_main.xml
            myAutoComplete = (CustomAutoCompleteView) findViewById(R.id.myautocomplete);

            myAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {

                    RelativeLayout rl = (RelativeLayout) arg1;
                    TextView tv = (TextView) rl.getChildAt(0);
                    myAutoComplete.setText(tv.getText().toString());

                }

            });

            // add the listener so it will tries to suggest while the user types
            myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this));

            // ObjectItemData has no value at first
            MyObject[] ObjectItemData = new MyObject[0];

            // set the custom ArrayAdapter
            myAdapter = new AutocompleteCustomArrayAdapter(this, R.layout.list_view_row, ObjectItemData);
            myAutoComplete.setAdapter(myAdapter);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertSampleData(){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOCATION,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();

                        try {

                            JSONArray jsonarray = new JSONArray(response);
                            for (int i = 0; i < jsonarray.length(); i++) {

                                String strValue = jsonarray.getString(i);
                                databaseH.create( new MyObject(strValue) );
                            }




                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("phrase", myAutoComplete.getText().toString());
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

    }
}
public class CustomAutoCompleteTextChangedListener implements TextWatcher {

    public static final String TAG = "AutoTextChangedListener";
    Context context;
    AutocompleteCustomArrayAdapter myAdapter;
    DatabaseHandler databaseH;
    CustomAutoCompleteView myAutoComplete;

    public CustomAutoCompleteTextChangedListener(Context context){
        this.context = context;
    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence userInput, int start, int before, int count) {

        try{

            // if you want to see in the logcat what the user types
            Log.e(TAG, "User input: " + userInput);

            MainActivity mainActivity = ((MainActivity) context);

            
            // These below 4 lines should be linked without "mainActivity" object.
            mainActivity.myAdapter.notifyDataSetChanged();

            
            MyObject[] myObjs = mainActivity.databaseH.read(userInput.toString());

            
            mainActivity.myAdapter = new AutocompleteCustomArrayAdapter(mainActivity, R.layout.list_view_row, myObjs);

            mainActivity.myAutoComplete.setAdapter(mainActivity.myAdapter);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}

.


Solution

  • Not to make matters too complicated, I simply added a textwatcher in MainActivity class instead of using a custom Textwatcher.

    public class MainActivity extends AppCompatActivity {
    
        CustomAutoCompleteView myAutoComplete;
    
        // adapter for auto-complete
        ArrayAdapter<MyObject> myAdapter;
    
        // for database operations
        DatabaseHandler databaseH;
        int layoutResourceId;
        private static final String LOCATION = "http://example.com/android/location";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            try{
    
                // instantiate database handler
                databaseH = new DatabaseHandler(MainActivity.this);
    
                // put sample data to database
                insertSampleData();
    
                // autocompletetextview is in activity_main.xml
                myAutoComplete = (CustomAutoCompleteView) findViewById(R.id.myautocomplete);
    
                myAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
                    @Override
                    public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {
    
                        RelativeLayout rl = (RelativeLayout) arg1;
                        TextView tv = (TextView) rl.getChildAt(0);
                        myAutoComplete.setText(tv.getText().toString());
    
                    }
    
                });
    
                // add the listener so it will tries to suggest while the user types
                myAutoComplete.addTextChangedListener(textwatch);
    
                // ObjectItemData has no value at first
                MyObject[] ObjectItemData = new MyObject[0];
    
                // set the custom ArrayAdapter
               // myAdapter = new AutocompleteCustomArrayAdapter(this, , ObjectItemData);
                myAdapter = new AutocompleteCustomArrayAdapter(this, R.layout.list_view_row, ObjectItemData);
                myAutoComplete.setAdapter(myAdapter);
    
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        TextWatcher textwatch = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                myAdapter.notifyDataSetChanged();
                MyObject[] myObjs = databaseH.read(s.toString());
                myAdapter = new AutocompleteCustomArrayAdapter(MainActivity.this, R.layout.list_view_row, myObjs);
                myAutoComplete.setAdapter(myAdapter);
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
            }
        };
    
        public void insertSampleData(){
    
            StringRequest stringRequest = new StringRequest(Request.Method.POST, LOCATION,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
    
                            Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
    
                            try {
    
                                JSONArray jsonarray = new JSONArray(response);
                                for (int i = 0; i < jsonarray.length(); i++) {
    
                                    String strValue = jsonarray.getString(i);
                                    databaseH.create( new MyObject(strValue) );
                                }
    
    
    
    
                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("phrase", myAutoComplete.getText().toString());
                    return params;
                }
    
            };
    
            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            requestQueue.add(stringRequest);
    
        }
    }