无法使用adapterName.clear()清除ArrayAdapter中的数据

时间:2018-05-24 19:03:25

标签: java android android-adapter custom-arrayadapter

我正在使用PreferenceScreen's widget,我希望每次更改ListView的值时,都应根据PreferenceScreen's widget中的结果显示结果。一切正常,除非我更改任何ListView的值而不是在adapter.clear()中显示新列表,而是在同一列表中添加值。显然,public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String>, SharedPreferences.OnSharedPreferenceChangeListener{ private static final String TAG = "MainActivity"; private static final int LOADER_INIT_KEY = 0; EditText titleTextView; Button searchButton; ListView listView; String query = ""; private ArrayList<String> authorsList = new ArrayList<>(); private ArrayList<BooksDetails> booksDetails = new ArrayList<>(); private String title = null, id = null; private CustomAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); titleTextView = findViewById(R.id.author_textView); searchButton = findViewById(R.id.search); listView = findViewById(R.id.list_view); /** * this declaration is needed */ adapter = new CustomAdapter(this, new ArrayList<BooksDetails>()); final ListView listView = findViewById(R.id.list_view_in_main_layout); listView.setAdapter(adapter); // getting instance of SharedPreference and attaching listener to it SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // any change in the SharedPreference will get notified // if user tweaks any settings sharedPreferences.registerOnSharedPreferenceChangeListener(this); // Search button searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // getting value from textView query = titleTextView.getText().toString(); Log.d(TAG, "onClick: "+query); // clearing the adapter adapter.clear(); // checking the network connection ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); assert connectivityManager != null; NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if(networkInfo != null && networkInfo.isConnected()) { if(query.length() != 0) { getSupportLoaderManager().initLoader(LOADER_INIT_KEY, null, MainActivity.this); closeKeyboard(); Log.d(TAG, "onClick: "); } else Toast.makeText(MainActivity.this, "Enter a title", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(MainActivity.this, "Not connected to internet", Toast.LENGTH_SHORT).show(); } } }); } private void closeKeyboard(){ // hiding keyboard after the search InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); View focusedView = this.getCurrentFocus(); if(focusedView != null) { try { assert inputMethodManager != null; inputMethodManager.hideSoftInputFromWindow(focusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }catch (AssertionError e){ Log.e(TAG, "closeKeyboard: Assertion error is thrown inputMethodManager is null", e); } } } @NonNull @Override public android.support.v4.content.Loader onCreateLoader(int id, @Nullable Bundle args) { Log.d(TAG, "onCreateLoader: "); // getting the SharedPreference which contains all the values of the Preference // SharedPreference for maxResults SharedPreferences maxResultsSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String maxResults = maxResultsSharedPreferences.getString(getString(R.string.settings_default_result_key), getString(R.string.settings_default_value_of_result)); // SharedPreference for OrderBy SharedPreferences orderBySharedPreference = PreferenceManager .getDefaultSharedPreferences(this); String orderByValue = orderBySharedPreference.getString(getString(R.string.settings_order_by_key), getString(R.string.settings_order_by_default)); // passing the minResults with query return new CustomLoader(this, query, maxResults, orderByValue); } @Override public void onLoadFinished(@NonNull android.support.v4.content.Loader loader, String s) { Log.d(TAG, "onLoadFinished: "); // clearing the adapter adapter.clear(); // after getting the raw json we are parsing it here try { JSONObject rootObject = new JSONObject(s); JSONArray itemsArray = rootObject.getJSONArray("items"); for(int i = 0;i < itemsArray.length();i++){ // getting each object in the array itemsArray JSONObject booksInfo = itemsArray.getJSONObject(i); // getting book id id = booksInfo.getString("id"); // getting the volumeInfo object JSONObject volumeInfo = booksInfo.getJSONObject("volumeInfo"); // getting title of the book title = volumeInfo.getString("title"); // getting the author JSONArray author = volumeInfo.getJSONArray("authors"); // getting all the members of author array for(int j = 0;j < author.length();j++){ authorsList.add(author.getString(j)); } if(title == null) { // if no title matches titleTextView.setText("No title matches"); } // adding details in the ArrayList bookDetails booksDetails.add(new BooksDetails(id, title, authorsList.get(0))); } adapter.addAll(booksDetails); } catch(Exception e){ Log.e(TAG, "onLoadFinished: exception in json parsing", e); } } @Override public void onLoaderReset(@NonNull android.support.v4.content.Loader loader) { Log.d(TAG, "onLoaderReset: "); // clearing the adapter adapter.clear(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.settings_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_settings){ Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(TAG, "onSharedPreferenceChanged: "); if(key.equals(getString(R.string.settings_order_by_key)) || key.equals(getString(R.string.settings_default_result_key))){ // clearing the adapter adapter.clear(); getSupportLoaderManager().restartLoader(LOADER_INIT_KEY, null, this); } } @Override protected void onRestart() { super.onRestart(); adapter.clear(); } 无效。

有人可以建议如何让它发挥作用吗?

这是我的MainActivity:

km$cluster <- sapply(km$cluster,function(x){rank(-km$centers)[x]})

}

1 个答案:

答案 0 :(得分:0)

您需要重置已传递给适配器的源列表。因为你在onCreate方法中放置了初始代码,该方法在创建活动时被调用一次。

而不是 adapter = new CustomAdapter(this, new ArrayList<BooksDetails>());

试试这个:

CustomAdapter adapter;
List<BooksDetails> srcList;

public void onCreate() {
srcList = new ArrayList<BookDetails>();
adapter = new CustomAdapter(this, srcList);
}

当您需要清除适配器时,请尝试使用

srcList().clear();
adapter.clear();
adapter.notifyDatasetChanged();