Your keyboard is not responding because displayResult
method is being executed on your main ui thread.
One of the possible solutions to handle this problem properly is using a IntentService
, for instance, you can do:
MyIntentService.java
public class MyIntentService extends IntentService {
//Each of these results represent a possible status of your service
public static final int RESULT_ERROR = -1;
public static final int RESULT_ENDED = 1;
public static final int RESULT_START = 0;
public static final String SERVICE_BROADCAST = MyIntentService.class.getName()+".Broadcast";
public MigrateService(){
super(MigrateService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
//Get the query
String queryText = intent.getStringExtra("MyQuery");
//Notify the activity that search has started
publishResult(RESULT_START, Bundle.EMPTY);
Bundle data = null;
try{
data = getDataWithRetrofit(queryText);
} catch (SomeException e){
//In case of error, notify the activity
publishResult(RESULT_ERROR, Bundle.EMPTY);
}
//Search is ended
publishResult(RESULT_ENDED, data);
}
public void publishResult(int resultCode, Bundle data){
Intent intent = new Intent(SERVICE_BROADCAST);
intent.putExtras(data);
intent.putExtra("resultCode",resultCode);
sendBroadcast(intent);
}
}
Basically, you have a Service
that fetches data in background thread and sends data to your Activity
when some event occurs (start/end).
On your Activity
class, you need to do the following:
1. Declare a BroadcastReceiver
instance:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.hasExtra("resultCode")) {
int resultCode = intent.getIntExtra("resultCode",MyService.STATUS_ERROR);
switch (resultCode) {
case MyIntentService.RESULT_START:
showIndeterminateProgress();
break;
case MyIntentService.RESULT_ENDED:
updateResultList(data);
break;
case MyIntentService.RESULT_ERROR:
showErrorMessage();
break;
}
}
}
};
2. Register and unregister your BroadcastReceiver
:
@Override
public void onResume(){
super.onResume();
registerReceiver(mReceiver, new IntentFilter(MyIntentService.SERVICE_BROADCAST));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
3. Start your Service:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
@Override
public boolean onQueryTextSubmit(String query)
{
return false;
}
@Override
public boolean onQueryTextChange(String newText)
{
if (!newText.trim().equals(""))
{
Intent i = new Intent(this, MyIntentService.class);
i.putExtra("MyQuery",newText);
startService(i);
return false;
}
}
});
Sources: