将自定义适配器、自定义自动完成文本视图和数据库添加到自定义文本观察器

Add custom adapter, custom autocompletetextview and database to custom textwatcher

我正在学习 Autocompetetextview 以从 Web 服务获取建议。为此,我使用了这个 tutorial。他们代码中的唯一问题是他们使用 MainActivity 在自定义文本观察器中链接了自定义适配器、自定义自动完成文本视图和本地数据库。我不想要这个,因为我想在多个 classes(MainActivity class 除外)中使用自定义自动完成文本视图。所以,我想知道我是否可以在不使用 MainActivity 作为对象的情况下获得这 3 个东西。

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();
        }

    }



}

.

为了不让事情变得太复杂,我只是在 MainActivity class 中添加了一个 textwatcher,而不是使用自定义 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);

    }
}