我正在学习Autocompetetextview以从Web服务获取建议。为此,我使用了这个tutorial。他们的代码中唯一的问题是他们使用MainActivity将自定义适配器,自定义autocompletetextview和本地数据库链接到自定义textwatcher中。我不想这样,因为我想在多个类(MainActivity类除外)中使用自定义autocompletetextview。所以,我想知道我是否可以在不使用MainActivity作为对象的情况下获得这三件事。
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();
}
}
}
答案 0 :(得分:1)
不要太复杂,我只是在MainActivity类中添加了一个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);
}
}