Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8917751
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T05:34:14+00:00 2026-06-15T05:34:14+00:00

I have 3 classes, I wish to use the autocomplete text box to show

  • 0

I have 3 classes, I wish to use the autocomplete text box to show user certain data (aka cities) from a web service (rest api). I’ve used this implementation on various features of my own application, but for some reason, there’s a synchronization problem within the textchangedlistener…

CitiesArrayAdapter.java (to show a different view, in my case the “city, state”):

package com.android.lzgo.adapters;

import java.util.ArrayList;
import java.util.List;

import com.android.lzgo.activities.LiftSearchActivity;
import com.android.lzgo.activities.R;
import com.android.lzgo.models.City;
import com.android.lzgo.models.Lift;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CitiesArrayAdapter extends ArrayAdapter<City> {

    private static final String TAG = CitiesArrayAdapter.class.getName();

    private final ArrayList<City> cities;
    private int viewResourceId;

    public CitiesArrayAdapter(Context context, int textViewResourceId, ArrayList<City> results) {
        super(context, textViewResourceId, results);
        this.cities = results;
        this.viewResourceId = textViewResourceId;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // assign the view we are converting to a local variable
        View v = convertView;

        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(viewResourceId, null);
        }

        City i = cities.get(position);

        Log.d(TAG, "Here is my value: " + i);

        if (i != null) {

            TextView tt = (TextView) v.findViewById(android.R.id.text1);

            Log.d(TAG, "Name: " + i.getName() + ", " + i.getProvince_name());

            if (tt != null){
                tt.setText("Name: " + i.getName() + ", " + i.getProvince_name());
            }
        }

        // the view must be returned to our activity
        return v;

    }

}

CitiesResponderFragment.java (this is how I get my values from my rest api):

package com.android.lzgo.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.android.lzgo.activities.LiftSearchActivity;
import com.android.lzgo.definitions.Constants;
import com.android.lzgo.models.City;
import com.android.lzgo.service.LzgoService;
import com.google.gson.Gson;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class CitiesResponderFragment extends LzgoResponderFragment {
    private static String TAG = CitiesResponderFragment.class.getName();

    private List<City> mCities;
    ArrayAdapter<City> adapter;
    private String enteredCharacters;
    LiftSearchActivity activity;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        activity = (LiftSearchActivity) getActivity();

        // This gets called each time our Activity has finished creating itself.
        getCities();

    }

    private void getCities() {

        if (mCities == null && activity != null) {
            Intent intent = new Intent(activity, LzgoService.class);
            intent.setData(Uri.parse(Constants.REST_CITIES_AUTOCOMPLETE));

            Bundle params = new Bundle();
            params.putString("search", getenteredCharacters());

            intent.putExtra(LzgoService.EXTRA_HTTP_VERB, LzgoService.GET);
            intent.putExtra(LzgoService.EXTRA_PARAMS, params);
            intent.putExtra(LzgoService.EXTRA_RESULT_RECEIVER, getResultReceiver());

            // Here we send our Intent to our RESTService.
            activity.startService(intent);
        }                
    }

    @Override
    public void onRESTResult(int code, String result) {
        Log.e(TAG, Integer.toString(code));
        Log.e(TAG, result);

        // Check to see if we got an HTTP 200 code and have some data.
        if (code == 200 && result != null) {
            mCities = getCitiessFromJson(result);

            adapter = activity.getArrayAdapter();

            adapter.clear();

            for( City city : mCities){
                //debugging
                Log.d(TAG, "City : " + city.getName());
                adapter.add(city);
                adapter.notifyDataSetChanged();
            }

            getCities();               

        }
        else {
            Activity activity = getActivity();
            if (activity != null && code == 400) {
                Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
            }
            else
                Toast.makeText(activity, "Failed to load lzgo data. Check your internet settings.", Toast.LENGTH_SHORT).show();
        }
    }

    private List<City> getCitiessFromJson(String json) {
        ArrayList<City> cityList = new ArrayList<City>();
        Gson gson = new Gson();

        try {
            JSONObject citiesWrapper = (JSONObject) new JSONTokener(json).nextValue();
            JSONArray  cities        = citiesWrapper.getJSONArray("cities");

            for (int i = 0; i < cities.length(); i++) {
                //JSONObject city = cities.getJSONObject(i);
                String jsonCity = cities.getString(i);
                City city = gson.fromJson( jsonCity, City.class );

                //Log.e(TAG, "Hurray! Parsed json:" + city.getString("name"));
                //cityList.add(city.getString("name"));
                cityList.add(city);
            }
        }
        catch (JSONException e) {
            Log.e(TAG, "Failed to parse JSON.", e);
        }

        return cityList;
    }

    public String getenteredCharacters() {
        return enteredCharacters;
    }

    public void setenteredCharacters(String characters) {
        this.enteredCharacters = characters;
    }


}

LiftSearchActivity.java (My FragmentActivity):

package com.android.lzgo.activities;

import java.util.ArrayList;

import com.android.lzgo.adapters.CitiesArrayAdapter;
import com.android.lzgo.fragment.CitiesResponderFragment;
import com.android.lzgo.models.City;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.DatePicker;

public class LiftSearchActivity extends FragmentActivity{

    private static final String TAG = LiftSearchActivity.class.getName();

    // User lift input
    private AutoCompleteTextView autoCityFrom;
    private AutoCompleteTextView autoCityTo;
    private DatePicker date;

    private CitiesArrayAdapter adapter;
    private ArrayList<City> mCities ;

    int year , month , day;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lift_search);

        mCities = new ArrayList<City>();

        adapter = new CitiesArrayAdapter(this,
                android.R.layout.simple_dropdown_item_1line, mCities);

        autoCityFrom = (AutoCompleteTextView) findViewById(R.id.cityFrom);
        autoCityTo = (AutoCompleteTextView) findViewById(R.id.cityTo);

        adapter.setNotifyOnChange(true);

        autoCityFrom.setAdapter(adapter);
        autoCityTo.setAdapter(adapter);

        autoCityFrom.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // no need to do anything
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (((AutoCompleteTextView) autoCityFrom).isPerformingCompletion()) {
                    return;
                }
                if (charSequence.length() < 2) {
                    return;
                }      

                String query = charSequence.toString();

                getCities(query);

            }

            public void afterTextChanged(Editable editable) {
            }
        });

        autoCityTo.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // no need to do anything
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (((AutoCompleteTextView) autoCityTo).isPerformingCompletion()) {
                    return;
                }
                if (charSequence.length() < 2) {
                    return;
                }

                String query = charSequence.toString();

                getCities(query);
            }

            public void afterTextChanged(Editable editable) { 
            }
        });

        date = (DatePicker) findViewById(R.id.dpResult);
    }

    public void searchLifts(View view) {

        Intent intent = new Intent(this, LiftsResultActivity.class);

        //While autocomplete doesn't work hardcore value...
        intent.putExtra("from", Integer.toString(9357)); // Sherbrooke
        intent.putExtra("to", Integer.toString(6193)); // Montreal
        intent.putExtra("date", Integer.toString(date.getMonth()+1) + "-" + Integer.toString(date.getDayOfMonth()) + "-" + Integer.toString(date.getYear()));
        startActivity(intent);
    }

    public void getCities(String query) {
        FragmentManager     fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        CitiesResponderFragment responder = (CitiesResponderFragment) fm.findFragmentByTag("RESTResponder");

        responder = new CitiesResponderFragment();
        responder.setenteredCharacters(query);
        ft.add(responder, "RESTResponder");

        ft.commit();
    }

    public CitiesArrayAdapter getArrayAdapter() {
        // TODO Auto-generated method stub
        return adapter;
    }

}

I get the correct result and all. But my service doesn’t seem to populate my array adapter in my activity, when I try to show my first “city”, my adapter contains nothing. I wonder if I have to put a notifydatasetchanged (I tried, but doesn’t work). I’m kind of confuse… any pointers?

While debugging the application I noticed that the properties mObjects of
the ArrayAdapter is cleared even if the associated ArrayList has
elements, and then properties mOriginalValues is filled with the
Strings loaded the first time.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T05:34:15+00:00Added an answer on June 15, 2026 at 5:34 am

    Without seeing the full code base(+ data), I don’t know if someone can pin point the reason for your code’s failure. But I think the problem comes more from the way you setup the whole auto complete related code than some obvious line error. Below I’ll try to address some of this issues(from my point of view) :

    First of all, in the TextWatcher from LiftSearchActivity you call the getCities() method which adds, each time the user modifies the auto complete text, a Fragment to the Activity. I really doubt you want this, you should probably look at having only one Fragment in the Activity on which to call a refresh(or update) method, passing it the new filter text. If the user rotates the phone those fragments will also be recreated because of the configuration change.

    Second, in the CitiesResponderFragment class you call the fragment’s getCities() method(if you don’t have any data) in onActivityCreated which start an update service(?!). Now related to the first point, you could end up doing a lot of unnecessary queries, for example if the user enter 4 characters and then decides to delete one of the characters as it was incorrect you’ll end up with 5 added fragments, from which 3 will make the service start/query for data.

    And last, I’m not sure if you understand how the AutoCompleteTextView works under the hood. In order to provide the drop down with the suggestions the AutoCompleteTextView widget will filter its adapter(adapter.getFilter()) and show as suggestions the items that match the filter. I don’t know if you set some threshold on the AutoCompleteTextView but initially the auto complete will be empty for the first 3 characters entered as you start with an empty list of items when you first setup the Activity. The first two characters will not show anything because you start with an empty list and you don’t add any new fragments(charSequence.length() < 2). The third character will most likely also not show anything, because the overhead of creating the fragment, starting the service and fetching the data will almost for sure be greater then doing the work of the adapter filtering(which will still see the initially empty list). I don’t know if you tested, but from this fourth character the adapter should have some elements in it and the filtering should show something. Clearing the adapter and adding new data in it willl only make that data available to the next character entered in the AutoCompleteTextView.

    The proper way of doing the filtering would be to further extend your adapter and implement the getFilter() method to return your own Filter implementation which would query the data store for new filtered items. The filtering method runs on a background thread, with a little work I think you could implement your current logic with the Service and the REST callback.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wish to have a map from classes to instances of each class. The
I have a Core Data Entity that receives periodic updates from a web service.
I have classes that are needed in both my web service and my server.
I'm making use of an interface for a set of classes. I have a
I have a PHP web application built with CodeIgniter MVC framework. I wish to
I have a class, with public API. I have other classes who inherit from
I have recently stated trying to use the newer style of classes in Python
I have a problem, I wish to use reflection to generate instances of one
I have a couple of classes that I wish to tag with a particular
I have read several articles on when to use nested classes, but none that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.