У меня такая проблема. У меня есть один ListView, и в первую очередь я его заполняю из базы данных SQLIte с помощью адаптера. Затем я реализую поиск и хочу поместить новые данные поиска в этот ListView (метод doMySearch), но я получаю тот же результат - данные не обновляются. Что можно сделать, чтобы исправить это? Вот код:Не удается обновить ListView с помощью адаптера
package com.example.citycode;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends ActionBarActivity {
ListView lvData,lvData1;
DBHelper db;
SimpleCursorAdapter scAdapter;
Cursor cursor;
Cursor cursor1;
final String LOG_TAG = "myLogs";
final String LOG_TAG1 = "myLogs1";
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// открываем подключение к БД
db = new DBHelper(this);
db.open();
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
// получаем курсор
cursor = db.getAllData();
startManagingCursor(cursor);
// Формируем столбцы сопоставления
String[] from = new String[] { DBHelper.COLUMN_r_name, DBHelper.COLUMN_region, DBHelper.COLUMN_code};
int[] to = new int[] { R.id.city_name, R.id.region_name, R.id.city_code };
// создааем адаптер и настраиваем список
scAdapter = new SimpleCursorAdapter(this, R.layout.item, cursor, from, to);
lvData = (ListView) findViewById(R.id.listdata);
lvData.setAdapter(scAdapter);
}
public void doMySearch(String query) {
lvData1 = (ListView) findViewById(R.id.listdata);
//Ищем совпадения
Log.d(LOG_TAG, "Before get the C");
cursor1 = db.fetchRecordsByQuery(query);
Log.d(LOG_TAG, "After get the C");
String t = Integer.toString(cursor1.getCount());
Log.d(LOG_TAG, t);
startManagingCursor(cursor1);
String[] from = new String[] { DBHelper.COLUMN_r_name, DBHelper.COLUMN_region, DBHelper.COLUMN_code};
int[] to = new int[] { R.id.city_name, R.id.region_name, R.id.city_code };
SimpleCursorAdapter scAdapter1;
scAdapter = new SimpleCursorAdapter(this,
R.layout.item, cursor1, from, to);
Log.d(LOG_TAG, "Setting the adapter");
//Обновляем адаптер
logCursor(cursor1);
lvData1.setAdapter(scAdapter);
Log.d(LOG_TAG, "Adapter was set");
}
//вывод в лог данных из курсора
void logCursor(Cursor c) {
if (c != null) {
if (c.moveToFirst()) {
String str;
do {
str = "";
for (String cn : c.getColumnNames()) {
str = str.concat(cn + " = " + c.getString(c.getColumnIndex(cn)) + "; ");
}
Log.d(LOG_TAG1, str);
} while (c.moveToNext());
}
} else
Log.d(LOG_TAG1, "Cursor is null");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_settings).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
db.close();
}
}
В ваш 'onCreate' вы сначала выполните поиск с помощью' doMySearch (query) ', а затем перейдете к' db.getAllData(); 'который заменит ваши результаты поиска. Для начала попробуйте вставить 'return' после' doMySearch (query) '. –