ListView не показывает правильный результат из запроса, если я вернусь ArrayList <CustomClass> из DB и использую SimpleAAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 ListView не показывает правильный результат из запроса, если я вернусь ArrayList <CustomClass> из DB и использую SimpleA

Сообщение Anonymous »

Извините, если я здесь дурак, но я пытаюсь использовать оператор как , чтобы найти все записи в таблице клиента (клиент), какое имя содержит строку.
Это код, который я использую:

Код: Выделить всё

   public Cursor searchClienteByRazonSocial(String razon) {
String where = CLIENTE_RAZONSOCIAL + " LIKE ? AND " + CLIENTE_ATENDIDO + " =?";
String[] whereArgs = { "%" + razon + "%" , "0" };

this.openReadableDB();
Cursor cursor = db.query(CLIENTE_TABLE, null, where, whereArgs, null,
null, null);

if (cursor != null) {
cursor.moveToFirst();
}
this.closeDB();
return cursor;

}
< /code>
Работает шаблон, но проблема возникает, когда я указываю имена с белым пространством в середине, например: < /p>
"Juan Carlos"
"Maria de Fatima"
< /code>
"Juan "
и «maria» совпадают и будут возвращены, но «Juan c» и «Maria d» ничего не возвращает. /> В этой базе данных таблица, которую я хочу запросить, называется: cliente и столбец razon_social
Это пример запроса, который я пытаюсь сделать из Android:
SELECT * FROM cliente WHERE razon_social LIKE '%jose l%'
< /code>
Am I missing something here?
EDIT
This is very strange , I think I kinda solve this, but I don't understand why this was happening.
This is what was trying to do
public class BuscarClientesActivity extends Activity implements
OnQueryTextListener, OnItemClickListener {

private ListView mResultsListView;
private SearchView mSearchView;

private QuickOrderDB mDB;
private ClientesListAdapter mClientesAdapter;
private ArrayList mClientes;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buscar_clientes);

//
mClientes = new ArrayList();
mResultsListView = (ListView) findViewById(R.id.resultadosClientesListView);
mClientesAdapter = new ClientesListAdapter(BuscarClientesActivity.this,
mClientes);

mSearchView = (SearchView) findViewById(R.id.buscarClientesSearchView);
mSearchView.setIconified(false);
mSearchView.setOnQueryTextListener(this);

mResultsListView.setOnItemClickListener(this);

// get database
mDB = new QuickOrderDB(getApplicationContext());

}

@Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()) {
displayResults(newText);
} else {
mResultsListView.setAdapter(mClientesAdapter);
}
return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
displayResults(query);
return false;
}

private void displayResults(String query) {
new FiltrarClientes().execute(query);
}
}
< /code>
Since I didn't want to query the DB inside the UI thread I moved all the code I use to pull the data from the DB to an AsyncTask as follows. This AsyncTask is coded as a inner class in the BuscarClientesActivity class shown above
class FiltrarClientes extends AsyncTask {

@Override
protected Cursor doInBackground(String... params) {
// get the query
String query = params[0];
Cursor resultados = BuscarClientesActivity.this.mDB
.searchClienteByRazonSocial(query);
return resultados;
}

@Override
protected void onPostExecute(Cursor result) {
// create a List of Map objects
ArrayList data = new ArrayList();

while (result.moveToNext()) {
HashMap map = new HashMap();
map.put("codigo","["+ String.valueOf(result.getInt(QuickOrderDB.CLIENTE_ID_COL))+ "]");
map.put("razonSocial",result.getString(QuickOrderDB.CLIENTE_RAZONSOCIAL_COL));
map.put("direccion",result.getString(QuickOrderDB.CLIENTE_DIRECCION_COL));
data.add(map);
}

// close the cursor
if (result != null) {
result.close();
}
// create the resource, from, and to variables
int resource = R.layout.resultados_clientes_item;
String[] from = { "codigo", "razonSocial", "direccion" };
int[] to = { R.id.itemCodClienteTextView,
R.id.itemRazonSocTextView, R.id.itemDireccionTextView };

// create and set the adapter
SimpleAdapter adapter = new SimpleAdapter(
BuscarClientesActivity.this, data, resource, from, to);
mResultsListView.setAdapter(adapter);

}
}
< /code>
As you can see, I was using a SimpleAdapter to display the data in the ListView. This was the code that was giving such a bad time. Then, after some trial and error, I realized that it wasn't a SQLite problem, but a problem with the type of adapter I was using, and this is the part I don't understand, because when I changed my code and instead of a SimpleAdapter I used a SimpleCursorAdapter everything work almost as expected.
private void displayResults(String query) {
// new FiltrarClientes().execute(query);
Cursor resultados = mDB
.searchClienteByRazonSocial(query);

if (resultados != null) {

String[] from = new String[] { QuickOrderDB.CLIENTE_ID,
QuickOrderDB.CLIENTE_RAZONSOCIAL,
QuickOrderDB.CLIENTE_DIRECCION };

int[] to = new int[] { R.id.busqCodClienteTextView,
R.id.busqRazonSocTextView, R.id.busqDireccionTextView };

@SuppressWarnings("deprecation")
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.resultados_clientes_item, resultados, from, to);
mResultsListView.setAdapter(cursorAdapter);
}
}
< /code>
As is shown above, I'm not using a AsyncTask, instead I'm running this query on the UI thread and also now I'm using a SimpleCursorAdapter.
Now this brings me to two questions:
  • First, what is the reason my code didn't work when I used a SimpleAdapter?
  • Second, do you know of any efficient way of querying a database without using a Content Provider. Would it be enough to use an AsyncTask??


Подробнее здесь: https://stackoverflow.com/questions/257 ... arraylistc
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»