I was doing some stuff using autocomplete textview in my application. I'm getting suggestion when user types anything. But, I have one query, when user types and taps on the suggested list on the autocomplete textview, then more suggestions comes up. I want to limit the search results when user taps on the list and don't want to show more options there. How can I overcome this situation.
This is my full class, which I'm working on:
public class WikiSuggestActivity extends Activity {
public String data;
public List<String> suggest;
public AutoCompleteTextView autoComplete;
public ArrayAdapter<String> aAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
suggest = new ArrayList<String>();
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoComplete.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) {
String newText = s.toString();
new getJson().execute(newText);
}
});
}
class getJson extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... key) {
String newText = key[0];
newText = newText.trim();
newText = newText.replace(" ", "+");
try {
HttpClient hClient = new DefaultHttpClient();
HttpGet hGet = new HttpGet(
"http://en.wikipedia.org/w/api.php?action=opensearch&search="
+ newText + "&limit=8&namespace=0&format=json");
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet, rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.getJSONArray(1).length(); i++) {
String SuggestKey = jArray.getJSONArray(1).getString(i);
suggest.add(SuggestKey);
}
} catch (Exception e) {
Log.w("Error", e.getMessage());
}
runOnUiThread(new Runnable() {
public void run() {
aAdapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.item, suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
}
}
Any guidance will be appreciated.
public class WikiSuggestActivity extends Activity {
public String data;
public List<String> suggest;
public AutoCompleteTextView autoComplete;
public ArrayAdapter<String> aAdapter;
public TextWatcher mTextWatcher = 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) {
String newText = s.toString();
new getJson().execute(newText);
}
};
public boolean watch = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
suggest = new ArrayList<String>();
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoComplete.addTextChangedListener( mTextWatcher );
autoComplete.setOnItemClickListener( new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
autoComplete.removeTextChangedListener( mTextWatcher );
aAdapter.clear();
watch = false;
}
});
}
class getJson extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... key) {
String newText = key[0];
newText = newText.trim();
newText = newText.replace(" ", "+");
try {
HttpClient hClient = new DefaultHttpClient();
HttpGet hGet = new HttpGet(
"http://en.wikipedia.org/w/api.php?action=opensearch&search="
+ newText + "&limit=8&namespace=0&format=json");
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet, rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.getJSONArray(1).length(); i++) {
String SuggestKey = jArray.getJSONArray(1).getString(i);
suggest.add(SuggestKey);
}
} catch (Exception e) {
Log.w("Error", e.getMessage());
}
if( watch )
runOnUiThread(new Runnable() {
public void run() {
aAdapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.item, suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
}
}
Related
I am newbie to android and working on a custom listView with custom adapter,I am having a listview and edittext,I want to add a searching feature using this,When user input some characters the listview should be filtered depending on the input,I have tried as below, Could someone help me to resolve this,
BusAdapter
public class BusAdapter extends BaseAdapter implements Filterable{
public ArrayList<Bus> BusArray;
private Context mContext;
// Original Values
private ArrayList<Bus> mDisplayedValues;
public BusAdapter(Context paramContext, ArrayList<Bus> BusArray) {
this.mContext = paramContext;
this.mDisplayedValues = BusArray;
this.BusArray = BusArray;
}
public int getCount() {
return this.BusArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_bus, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.tv_rtname = ((TextView) paramView.findViewById(R.id.tv_rtname));
localViewholder.tv_from = ((TextView) paramView.findViewById(R.id.tv_from));
localViewholder.tv_to = ((TextView) paramView.findViewById(R.id.tv_to));
localViewholder.tv_freq = ((TextView) paramView.findViewById(R.id.tv_fr));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.tv_from
.setText(BusArray.get(paramInt).getRoute_from());
localViewholder.tv_to
.setText(BusArray.get(paramInt).getRoute_to());
localViewholder.tv_rtname
.setText(BusArray.get(paramInt).getRoute_name());
return paramView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
mDisplayedValues = (ArrayList<Bus>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<Bus> FilteredArrList = new ArrayList<Bus>();
if (BusArray == null) {
BusArray = new ArrayList<Bus>(mDisplayedValues); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = BusArray.size();
results.values = BusArray;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < BusArray.size(); i++) {
String data = BusArray.get(i).getRoute_name();
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(new Bus(BusArray.get(i).route_id,BusArray.get(i).route_name,BusArray.get(i).route_details,BusArray.get(i).route_from,BusArray.get(i).route_to));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
//get filter
//end
static class Viewholder {
TextView tv_from;
TextView tv_to;
TextView tv_rtname;
TextView tv_freq;
}
}
Activity
public class BusTimingActivity extends AppCompatActivity {
ListView lv_bus;
ArrayList<Bus> busList;
ProgressDialog pDialog;
InputStream inputStream = null;
String result;
BusAdapter adapter;
EditText et_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_bus_timings);
lv_bus = (ListView)findViewById(R.id.lv_bus);
et_search = (EditText)findViewById(R.id.et_search);
busList = new ArrayList<>();
et_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
new GETBUSROUTES().execute();
}
//GET ALL BUS ROUTES..
public class GETBUSROUTES extends AsyncTask<Void, Void, Void> {
StringEntity se;
String url;
#Override
protected void onPreExecute() {
super.onPreExecute();
busList.clear();
pDialog = new ProgressDialog(BusTimingActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
busList.clear();
}
#Override
protected Void doInBackground(Void... params) {
url = Const.API_URL;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> valueparams = new ArrayList<NameValuePair>();
valueparams.add(new BasicNameValuePair("form_type", "all_bus_routes"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(valueparams));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String json = "";
//getting string entity to http..!!!
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
result = total.toString();
try {
JSONArray results = new JSONArray(result);
for (int i = 0; i<results.length() ; i++) {
JSONObject c = results.getJSONObject(i);
Bus bus = new Bus();
bus.setRoute_id(c.getString("route_id"));
bus.setRoute_details(c.getString("route_details"));
bus.setRoute_from(c.getString("route_from"));
bus.setRoute_to(c.getString("route_to"));
bus.setRoute_name(c.getString("route_name"));
busList.add(bus);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("====RESPONSE FOR BUSES====>" + result.toString());
} else
result = "Did not work!";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// execute HTTP post request
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
//
if(busList.size()>0){
adapter = new BusAdapter(BusTimingActivity.this,busList);
lv_bus.setAdapter(adapter);
adapter.notifyDataSetChanged();
}else{
Toast.makeText(BusTimingActivity.this,"No Routes Found",Toast.LENGTH_SHORT).show();
}
}
}
Bus.java
public class Bus {
public String route_id;
public String route_name;
public Bus(String route_id, String route_name, String route_details, String route_from, String route_to) {
this.route_id = route_id;
this.route_name = route_name;
this.route_details = route_details;
this.route_from = route_from;
this.route_to = route_to;
}
public Bus() {
}
public String route_details;
public String getRoute_from() {
return route_from;
}
public void setRoute_from(String route_from) {
this.route_from = route_from;
}
public String getRoute_id() {
return route_id;
}
public void setRoute_id(String route_id) {
this.route_id = route_id;
}
public String getRoute_name() {
return route_name;
}
public void setRoute_name(String route_name) {
this.route_name = route_name;
}
public String getRoute_details() {
return route_details;
}
public void setRoute_details(String route_details) {
this.route_details = route_details;
}
public String getRoute_to() {
return route_to;
}
public void setRoute_to(String route_to) {
this.route_to = route_to;
}
public String route_from;
public String route_to;
}
Since it seems you are just filtering on the getRoute_name() it may be easier to extend ArrayAdapter<Bus> which will do the filtering for you and then override the toString() for your Bus object to return the route name.
I don't think it's your filtering problem, but the getItem() should return a Bus object from your array list and not an Integer.
As #Daniel Wilson pointed out, your code is a bit difficut to read because of your variables that start with capial letters, it makes it look like a static method call.
Im currently working on an online mobile app. i have a listview populated from the database. in my listview, im trying to filter the data from the inputted data in my edittext above my listview.But i have hard time working on search. Im using a custom arrayadapter for my listview but the listview is not being filtered. It shows the same data. Please anyone out there to help me fix my problem. thanks :)
heres my ListofCityAdapter.class
public class ListofCityAdapter extends ArrayAdapter implements Filterable{
int groupid;
ArrayList<City> records;
ArrayList<City> items;
Context context;
public ListofCityAdapter(Context context, int vg, int id, ArrayList<City> objects) {
super(context, vg, id, objects);
this.context = context;
groupid = vg;
this.records = objects;
} public int getCount() {
return records.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(groupid, parent, false);
TextView textName = (TextView) itemView.findViewById(R.id.city_name);
textName.setText(records.get(position).getCityName());
TextView cityregion = (TextView)itemView.findViewById(R.id.city_region);
cityregion.setText(records.get(position).getRegion());
ImageView image = (ImageView)itemView.findViewById(R.id.image);
//mage.setImageResource(R.drawable.progress);
new DownloadImageTask(image).execute(records.get(position).getImage());
return itemView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<City> results = new ArrayList<City>();
if (records == null)
records = items;
if (constraint != null) {
if (records != null && records.size() > 0) {
for (final City g : records) {
if (g.getCityName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
items = (ArrayList<City>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
and here's my ListOfCityPage.class
public class ListofCity extends Fragment implements AdapterView.OnItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
Spinner filter;
ListofCityAdapter cityAdapter;
GridView listCity;
ArrayList<City> list;
ArrayList<City> records;
int id;
// SharedPreferences.Editor citylist;
String line=null;
String filtering,cityname,text;
SwipeRefreshLayout swipeLayout;
View view;
public ListofCity(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_listof_city, container, false);
context = getActivity();
records = new ArrayList<City>();
listCity = (GridView) view.findViewById(R.id.cities);
cityAdapter = new ListofCityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
list = new ArrayList<City>();
filter = (Spinner) view.findViewById(R.id.filter);
String categories[] = getResources().getStringArray(R.array.filtering);
ArrayAdapter<String> cat = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);
cat.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
filter.setAdapter(cat);
listCity.setTextFilterEnabled(true);
filter.setOnItemSelectedListener(this);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(), City_attractions.class);
Toast.makeText(getActivity(), "Opening", Toast.LENGTH_LONG).show();
cityname = records.get(position).getCityName();
String info = records.get(position).getDescription();
String area = records.get(position).getArea();
String population = records.get(position).getPopulation();
String region = records.get(position).getRegion();
String province = records.get(position).getProvince();
myIntent.putExtra("cityname", cityname);
myIntent.putExtra("cityinfo", info);
myIntent.putExtra("cityarea", area);
myIntent.putExtra("citypopulation", population);
myIntent.putExtra("cityregion", region);
myIntent.putExtra("cityprovince", province);
startActivity(myIntent);
}
});
final EditText search = (EditText)view.findViewById(R.id.inputSearch);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
text = search.getText().toString().toLowerCase(Locale.getDefault());
filter(text);
}
});
return view;
}
public void filter(String charText) {
charText = text.toLowerCase(Locale.getDefault());
list.clear();
if (charText.length() == 0) {
list.addAll(records);
} else {
for (City wp : records) {
if (wp.getCityName().toLowerCase(Locale.getDefault())
.contains(charText)) {
list.add(wp);
}
}
}
cityAdapter.notifyDataSetChanged();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
fetchCity fetch = new fetchCity();
switch (position){
case 0:
filtering ="All";
fetch.execute();
break;
case 1:
filtering ="Alphabetically";
fetch.execute();
break;
case 2:
filtering ="Region";
fetch.execute();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeLayout.setRefreshing(false);
new fetchCity().execute();
}
}, 5000);
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
/**
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
**/ }
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("filter", filtering));
try
{
records.clear();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getcity.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("cityName"));
p.setArea(json_data.getString("area"));
p.setPopulation(json_data.getString("population"));
p.setImage(json_data.getString("path"));
p.setDescription(json_data.getString("city_info"));
p.setProvince(json_data.getString("province"));
p.setRegion(json_data.getString("region"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
To filter a listView with EditText, the simplest way is to use a textwatcher. Use the onTextChanged method of the textwatcher rather than afterTextChanged. And i think you probably don't need the public void filter(xyz) method as well. This code will probably work for you:
inputText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
YouActivityName.this.cityAdapter.getFilter().filter(s);
cityAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
Here, It is my java file
public class Create_Event extends SherlockFragment
implements OnClickListener {
class Organizer extends AsyncTask<Void, Void, Object> {
private ProgressDialog pdia;
protected void onPreExecute() {
super.onPreExecute();
pdia = new ProgressDialog(getActivity());
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected Object doInBackground(Void... params) {
try {
HttpClient httpclient1 = new DefaultHttpClient();
HttpPost httppost1 = new HttpPost(Constants.BASE_URL
+ "mobile_logins/all_my_event");
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1);
nameValuePairs1.add(new BasicNameValuePair("id", Constants.id));
httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse response1 = httpclient1.execute(httppost1);
String _response1 = EntityUtils.toString(response1.getEntity());
Log.e("test", _response1);
jsobj1 = new JSONObject(_response1);
orr = jsobj1.getJSONArray("organizers");
String orggg = orr.toString();
Log.e("Organization", orggg);
return jsobj1;
} catch (Exception e) {
e.printStackTrace();
Log.e("Fail 1", e.toString());
return e;
}
}
protected void onPostExecute(Object jsobj) {
pdia.dismiss();
String post = jsobj.toString();
Log.e("event_rese", post);
int len = orr.length();
Log.e("json_posexe", orr.toString());
Log.e("Onpostexe_arrlength", String.valueOf(len));
try {
JSONArray JA = orr;
JSONObject json1 = null;
final String[] host1 = new String[orr.length()];
final String[] host_id=new String[orr.length()];
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < host1.length; i++) {
list.add(host1[i]);
}
Log.e("onpostexe_list",list.toString());
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
organization=sp.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
if (json instanceof JSONObject) {
asyncrun = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
} else {
ExecptionHandler.register(getActivity(), (Exception) jsobj);
}
}
}
}
}
Here, I need id of the selected organization from spinner. The id and organization name came from Jsonobject(here jsobj1). How to get id of selected item from jsonobject? Is it possible?? Please Help...
Create a Organization bean as below with method #Override toString()
public class Organization {
private Integer orgId; // Long etc.
private String orgName;
// more properties if you need
#Override // Mandatory
public String toString() {
return orgName; // Return anything, what you want to show in spinner
}
// Getter & Setter
}
Then Create a java.util.List<Organization> organizationList; from your API response JSONArray or any other way. And make and set ArrayAdapter<Organization> to load Spinner options.
List<Organization> organizationList = ... // init using JSON Data OR any how;
ArrayAdapter<Organization> orgAdapter = new ArrayAdapter<Organization>(this, android.R.layout.simple_spinner_item, organizationList);
orgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner mySpinner = findViewById(R.id.orgSpinner);
mySpinner.setAdapter(orgAdapter);
Now get selected Organization and its Properties in any Click/Change Event like below
// In any OnClick / OnSelect event
Organization selectedOrganization = (Organization) mySpinner.getSelectedItem();
Integer orgId = selectedOrganization.getOrgId();
String orgName = selectedOrganization.getOrgName();
// and if you have more properties
Yes,it is Possible, try like below.
HashMap<String,String> map_values = new HashMap<String,String>();
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
map_values.put(host1[i],host_id[i]);
}
and spinner
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
String value = sp.getSelectedItem().toString();
String id = map_values.get(value);
Log.v("id",""+id);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
mSpinner.getSelectedItemId(); // here is your selected item's Id.
BTW google first, ask later :)
I am trying to do the autocompleteTextView. I am trying the Wiki Example. For Wiki it works. But for my own api its not working. I am trying to call by lastname. I tried using the jSonObject. But looks like i am making some mistake. Here is my Code.
public class WikiSuggestActivity extends Activity {
public String data;
public List<String> suggest;
public AutoCompleteTextView autoComplete;
public ArrayAdapter<String> aAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
suggest = new ArrayList<String>();
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoComplete.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) {
String newText = s.toString();
new getJson().execute(newText);
}
});
}
class getJson extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... key) {
String newText = key[0];
newText = newText.trim();
newText = newText.replace(" ", "+");
try{
HttpClient hClient = new DefaultHttpClient();
// HttpGet hGet = new HttpGet("http://en.wikipedia.org/w/api.php?action=opensearch&search="+newText+"&limit=8&namespace=0&format=json");
HttpGet hGet = new HttpGet("http://api.xyz.com?response_format=json&version=2.0&name="+newText);
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet,rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
JSONObject mJsonObject = new JSONObject();
for(int i=0;i<jArray.getJSONArray(1).length();i++){
String SuggestKey = jArray.getJSONArray(1).getString(i);
// mJsonObject = jArray.getJSONObject(i);
// mJsonObject.getString("lastname");
suggest.add(SuggestKey);
}
}catch(Exception e){
Log.w("Error", e.getMessage());
}
return null;
}
public void onPostExecute(Void result) {
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
}
}
Here is my JSON and its a valid JSON
{
"body": {
"players": [
{
"firstname": "abc",
"lastname": "def"
},
{
"firstname": "xyz",
"lastname": "abc"
},
]
},
"statusCode": 200
}
Edit:
Parse your json like this
JSONObject obj=new JSONObject(data);
JSONObject obj2=obj.getJSONObject("body");
JSONArray array=obj2.getJSONArray("players");
for(int i=0;i<array.length();i++)
{
JSONObject playerinfo=array.getJSONObject(i);
String lastname=playerinfo.getString("lastname");
suggest.add(lashname);
}
You can Capture the results from the doInBackGround by returning the result and use it in the onPostExecute .
You are trying to update UI from non UI thread, because doInBackground not running in the UI thread.
put thsi code in onPostExecute
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
You can get the suggest by returning the value in doInBackground
Take your doInBackground of type ArrayList
and return the suggest
you'll the suggest in the onPostExecute as a method parameter, pass it to the adapter
I'm trying to trap event listener on the auto-suggest for my application. i'm populating the list using wiki-suggest : http://en.wikipedia.org/w/api.php?action=opensearch&search=%22bike%22&limit=8&namespace=0&format=json.
I'm getting all the things right but now I want to just click on the item of the list and bring the string to the next activity. I have gone through : http://developer.android.com/reference/android/widget/AutoCompleteTextView.html#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
But that is not giving me idea that how can I implement that.
I'm pasting my code here for the auto-suggest populating. Please suggest how to overcome this problem.
#Override
protected String doInBackground(String... key) {
String newText = key[0];
newText = newText.trim();
newText = newText.replace(" ", "+");
try {
HttpClient hClient = new DefaultHttpClient();
HttpGet hGet = new HttpGet(
"http://en.wikipedia.org/w/api.php?action=opensearch&search="
+ newText + "&limit=8&namespace=0&format=json");
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet, rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.getJSONArray(1).length(); i++) {
String SuggestKey = jArray.getJSONArray(1).getString(i);
suggest.add(SuggestKey);
}
} catch (Exception e) {
Log.w("Error", e.getMessage());
}
runOnUiThread(new Runnable() {
public void run() {
aAdapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.item, suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
This is how I get new suggestions from wiki-suggest:
autoComplete = (AutoCompleteTextView) findViewById(R.id.text);
autoComplete.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String newText = s.toString();
new getJson().execute(newText);
}
});
Update from comments
Where you initialize autoComplete, probably in onCreate(), add your OnItemClickListener like this:
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoComplete);
autoComplete.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = ((TextView) view).getText().toString();
new getJson().execute(text);
}
});
Solved that. Just has to pass the whole string to the URL on ItemClickListener.