Wednesday, July 16, 2014

android custom autocompletetextview load data from web service

Autocompletetextview An editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.
The drop down can be dismissed at any time by pressing the back key or, if no item is selected in the drop down, by pressing the enter/dpad center key.
The list of suggestions is obtained from a data adapter and appears only after a given number of characters defined by the threshold.
The following code snippet is help to show suggestions in autocompletextview .this suggestion data load  from webservice.
activity:
package:com.gaddamsraj.blogspot.com
class autocompletextview extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.msappcategories);
        txteditcomment = (AutoCompleteTextView) actionBarLayout..findViewById(R.id.txteditcomment);
     
         txteditcomment.setOnItemClickListener(mssubcategory.this);

txteditcomment.addTextChangedListener(new TextWatcher(){

public void afterTextChanged(Editable editable) {
// TODO Auto-generated method stub

}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {

ProductSearchAutoText adapter = new ProductSearchAutoText(activity.this,
R.layout.listitem_search, "", "", "");//custom adapter class
adapter.notifyDataSetChanged();
                             txteditcomment.setDropDownHeight(135);
                              txteditcomment.setAdapter(adapter);


}

});

}
ArrayAdapter
public class ProductSearchAutoText extends ArrayAdapter<ProductSearch>
{
private String apikey;
Context context;
int layoutResourceId;
private URLConnection ucon;
private String mshost;
ArrayList<ProductSearch> data = new ArrayList<ProductSearch>();
ArrayList<ProductSearch> resultList = null;
String subcatid="";
String userid="";
String srchmem="";
private String prev_last_cat_id="";
public ProductSearchAutoText(Context context, int layoutResourceId,String category,String userid,String srchmem) {
super(context, layoutResourceId);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.subcatid=category;
this.userid=userid;
this.srchmem=srchmem;

this.mshost= context.getString(R.string.mshost);
this.apikey = context.getString(R.string.apikey);
}
@Override
public int getCount() {
if (resultList==null)
{
return 0;
}
else
{
return resultList.size();
}
}

@Override
public ProductSearch getItem(int index) {
return resultList.get(index);
}
@Override
public long getItemId(int position)
{
return resultList.get(position).hashCode();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.productautosearch, null);
}
ProductSearch o = resultList.get(position);
if (o != null) {

TextView catID=(TextView)v.findViewById(R.id.catID);
TextView reviewCount=(TextView)v.findViewById(R.id.reviewCount);
catID.setText(o.getCatID());
reviewCount.setText(o.getReviewCount());
}
return v;
}
@Override
public Filter getFilter()
{
Filter myFilter = new Filter()
{
@Override
protected FilterResults performFiltering(CharSequence constraint)
{
FilterResults filterResults = new FilterResults();
if(constraint != null)
{
try {

resultList = autocomplete(constraint.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Assign the data to the FilterResults
filterResults.values = resultList;
if (resultList==null)
{
filterResults.count = 0;
}
else
{
filterResults.count = resultList.size();
}
}
return filterResults;
}

@Override
protected void publishResults(CharSequence contraint, FilterResults results)
{
if(results != null && results.count > 0)
{
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
@SuppressWarnings("deprecation")
private ArrayList<ProductSearch> autocomplete(String input) throws IOException {
ArrayList<ProductSearch> resultList = null;
if(Connected)//network
{

String url1="http://test.com="+input;//append the input string with URL
try {
URL myURL = new URL(url1);  

ucon = myURL.openConnection();
ucon.setRequestProperty("Content-Language", "en-US");
ucon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
ucon.setRequestProperty("Connection", "Keep-Alive");

/* Define InputStreams to read * from the URLConnection. */
InputStream is = ucon.getInputStream()     ;
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
if(sb!=null)
{
if (! sb.toString().contains("failure") || ! sb.toString().equalsIgnoreCase(""))
{
JSONObject jsonResponse;

jsonResponse = new JSONObject(sb.toString());

JSONArray results = jsonResponse.getJSONArray("results");
if(results!=null)
{
if(results.length()>0)
                        {
   int i;
   i=0;
  resultList = new ArrayList<ProductSearch>(results.length());
  for(i=0;i<results.length();i++)
                          {
JSONObject jsonR = results.getJSONObject(i);
                       ProductSearch psearch=new ProductSearch();
       String cat_id= jsonR.getString("cat_id");
      String Reviewcnt= jsonR.getString("cat_id");
psearch.setCatID(cat_id);
               psearch.setReviewCount(Reviewcnt);
resultList.add(psearch);

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



}
ProductSearch:
public class ProductSearch {
public String catID="";

public String reviewCount="";
       
       public String getCatID() {
return catID;
}
public void setCatID(String catID) {
this.catID = catID;
}
public String getReviewCount() {
return reviewCount;
}
public void setReviewCount(String reviewCount) {
this.reviewCount = reviewCount;
}
}