Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Evan Dix
1,641 PointsSearch bar that searches through a json array.
I am trying to create search bar that searches through json data from a server and presents the results in a ListView. The data is in the form of an array. For Example
ProductList: [
{ ProductCode: "10012010", ProductName: "Kell", ProductGrammage: "120 gm", ProductBarcode: "890123456789", ProductCatCode: "40", ProductCatName: "Packed Food and Condiments", ProductSubCode: "4001", ProductSubCodeName: "Breakfast & Cereals", ProductMRP: "120", ProductBBPrice: "115" },
ect...
]
So lets say i type in Kell in the search bar. I want this Kell object to pop up.
1 Answer
Sanat Tripathi
8,109 PointsHave you looked at AutoCompleteTextView? I think you need that, if you are trying to build a suggestion box over a single attribute like "ProductName" in your example.
If you are searching on a single attribute then I would go about implementing it the following way:
//A method that would return you the list that you wanna populate in that suggestion box
private List<String> getProductNamesList(JSONObject dataReceived, String attributeName)
{
List<String> productNames = new ArrayList<String>();
JSONArray arr = dataReceived.optJSONArray("ProductList"); //From your json data example
for(int i = 0; i < arr.length(); i++)
{
productNames.add(arr.optJSONObject(i).optString(attributeName));
}
return productNames;
}
And then somewhere in your main view (which holds the suggestion box), I would use the built-in android simple adapter:
List<String> productNames = getProductNamesList(data, requiredAttribute); //requiredAttribute can be "ProductName" here
AutoCompleteTextView textView = (AutoCompleteTextView) mView.findViewById(R.id.someAutoTextViewInYourLayout);
ArrayAdapter<String> mSuggestionsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, productNames);
textView.setAdapter(mSuggestionsAdapter);
This might not be the efficient way or the exact thing that you might be looking for but I hope it helps!