custom suggestions through webservice json in search widget of actionbar

  • Replies:1
Joy
  • Forum posts: 4

Aug 31, 2013, 10:50:49 AM via Website

I am developing app on android4.1 , phonegap2.9 and jquerymobile 1.3. I want to generate search widget suggestions using webservice which returns me movie titles in json format. My Mainactivity extends from DroidGap. I have created content provider and linked it through manifest. But somehow not successful in attaching. Whenever i type search letter in search widget it throws error 'illegal argument exception column 'wanted' (i.e the movie name entered in search does not exist. plz help

public class WSSuggestionProvider1 extends ContentProvider {

private static final String tag = "WSSuggestionProvider1";
static final int SUGGESTIONS_MOVIE = 1;
static final int SEARCH_MOVIE = 2;
private static final int GET_MOVIE = 3;
public static final String _ID = "_id";

UriMatcher mUriMatcher = buildUriMatcher();

private UriMatcher buildUriMatcher(){
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS_MOVIE);
uriMatcher.addURI(AUTHORITY, "movies", SEARCH_MOVIE);
uriMatcher.addURI(AUTHORITY, "movies/#", GET_MOVIE);
return uriMatcher;
}

@Override
public boolean onCreate() {

Log.d(tag,"************************contentprovider onCreate called");
return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {

Cursor c = null;
switch(mUriMatcher.match(uri)){
case SUGGESTIONS_MOVIE :
c = callwebservice(selection);
break;
case SEARCH_MOVIE :
//c = callwebservice(selectionArgs);
break;
case GET_MOVIE :
String id = uri.getLastPathSegment();
c = callwebservice(id);
}

return c;
}



public String getType(Uri uri) {
throw new UnsupportedOperationException();
}

public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}

public int delete(Uri uri, String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException();
}

public int update(Uri uri, ContentValues values,
String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException();
}

/************* webservice call which returns cursor with movie titles *****************/
public static Cursor callwebservice(String query)
{
List<String> list = new ArrayList<String>();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("query",query));
String result;
MatrixCursor matrixCursor=null;
MergeCursor mergeCursor=null;
Cursor cursor=null;
try {
result = CustomHttpClient.executeHttpPost("url",postParameters);

JSONArray array;

JSONObject o = new JSONObject(result);
array = o.getJSONArray("images_arr");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String url = obj.getString("Title");
list.add(url);

matrixCursor = new MatrixCursor(new String[] { "_ID","Title" });
String ival=new Integer(i).toString();
matrixCursor.addRow(new Object[] {ival,url});

// Merge your existing cursor with the matrixCursor you created.
mergeCursor = new MergeCursor(new Cursor[] { matrixCursor, cursor });
}

return mergeCursor;


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

}
}

/***************** json string returned by above webservice *****************/
{"images_arr":[{"Campaign_ID":"1","PATH_NAME":"wanted1.jpg","Title":"Wanted","Description":"Wanted movie"},{"Campaign_ID":"2","PATH_NAME":"3idiots1.jpg","Title":"3 idiots","Description":"Upon release, the film broke all opening box office records in India. It was the highest-grossing film in its opening weekend in India and had the highest opening day collections for a Bollywood film."}]}

/*************** MainActivity ************************************************************/

public class MainActivity1 extends DroidGap implements SearchView.OnQueryTextListener,SearchView.OnSuggestionListener,SearchView.OnCloseListener{

MenuItem searchItem;
private SearchView mSearchView;
private TextView mStatusView;

List<String> list = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
super.setBooleanProperty("showTitle", true);

super.onCreate(savedInstanceState);
super.init();

super.setIntegerProperty("loadUrlTimeoutValue", 120000);

// implementation to load urls of welcome page

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.

super.onCreateOptionsMenu(menu);

getMenuInflater().inflate(R.menu.main, menu);
searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchItem.getActionView();
mSearchView.setQueryHint(getString(R.string.search_hint));
setupSearchView(searchItem);

return true;


}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
//menu implementations
default:
return super.onOptionsItemSelected(item);
}
}

public boolean onQueryTextChange(String newText) {
List<String> list = new ArrayList<String>();

if(newText.equals(""))
{

return false;
}
else
{
Cursor cursor = WSSuggestionProvider1.callwebservice(newText); // Called explicitely webservice as not getting automatically called and show data in suggestions

if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("Title"));

// do what ever you want here
list.add(data);
cursor.moveToNext();
}while(!cursor.isAfterLast());
}

cursor.close();

if(cursor.getCount() != 0)
{
String[] columns = new String[list.size()];
list.toArray(columns); // fill the array

int[] columnTextId = new int[] { android.R.id.text1};
SimpleCursorAdapter sCA=null;
try
{
sCA = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1, cursor,
columns , columnTextId);
}
catch(Exception e)
{
System.out.println("Error "+e);
}

mSearchView.setSuggestionsAdapter(sCA);
return true;
}
else
{
return false;
}

}
//return true;

}

public boolean onQueryTextSubmit(String query) {
//mStatusView.setText("Query = " + query + " : submitted");
System.out.println("----------onQueryText submitted");
mSearchView.clearFocus();

MenuItem searchMenuItem = getSearchMenuItem();
if (searchMenuItem != null) {
searchMenuItem.collapseActionView();
}
return true;
}

public boolean onClose() {
return false;
}
protected boolean isAlwaysExpanded() {
return true;
}

public MenuItem getSearchMenuItem() {
return searchItem;
}

private void setupSearchView(MenuItem searchItem) {

if (isAlwaysExpanded()) {
mSearchView.setIconifiedByDefault(false);
} else {
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}

SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null) {
List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();

SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
for (SearchableInfo inf : searchables) {
if (inf.getSuggestAuthority() != null
&& inf.getSuggestAuthority().startsWith("applications")) {
info = inf;
}
}
mSearchView.setSearchableInfo(info);
}

mSearchView.setOnQueryTextListener(this);
mSearchView.setOnSuggestionListener(this);
mSearchView.setIconifiedByDefault(true);
mSearchView.setOnCloseListener(this);
}

@Override
public boolean onSuggestionSelect(int position) {

return false;
}

@Override
public boolean onSuggestionClick(int position) {
// implementations after suggestin click
return true;
}

}

/************************************** searchable.xml **********************************************/

android:searchSuggestIntentAction="android.intent.action.VIEW"
android:searchSuggestIntentData="content://com.example.cachedemo.WSSuggestionProvider1/movies"
android:searchSuggestAuthority="com.example.cachedemo.WSSuggestionProvider1"

/*************************** Androidmanifest.xml ******************************************/
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.wssearchdemo.MainActivity1"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden|keyboard|locale" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchActivity" />

</activity>

<activity
android:name="com.example.wssearchdemo.SearchActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden|keyboard|locale"
android:launchMode="singleTop">

<!-- This intent-filter identifies this activity as "searchable" -->

<intent-filter >
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>

<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>


<provider android:name=".WSSuggestionProvider1"
android:authorities="com.example.wssearchdemo.WSSuggestionProvider1"
android:exported="false" />
</application>

</manifest>

Reply
Joy
  • Forum posts: 4

Sep 10, 2013, 9:23:53 AM via Website

I am struggling with this problem. Can any one plz help ? Not able to trace out what is going wrong.

Reply