3

我想在我的 android 应用程序中实现 google 类型搜索,为此我使用了自动完成 textview,当我一个一个输入字符时它非常有效,但是当我同时输入多个字符时会出现问题,我的应用程序显示一个对话框并强制关闭. 提前致谢

public class Activity_ListItem extends Activity {
public Context mContext;
// views declaration
public AutoCompleteTextView txtAutoComplete;
public ListView lvItems;
// arrayList for Adaptor
ArrayList<String> listItems;
// getting input from AutocompleteTxt
String strItemName;
// making Adaptor for autocompleteTextView
ArrayAdapter<String> adaptorAutoComplete;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // for showing full screen
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_listitem);
    mContext = this;
    listItems = new ArrayList<String>();
    // Declaring and getting all views objects
    Button btnShare = (Button) findViewById(R.id.ListItem_btnShare);
    Button btnSort = (Button) findViewById(R.id.ListItem_btnSort);
    lvItems = (ListView) findViewById(R.id.ListItem_lvItem);
    txtAutoComplete = (AutoCompleteTextView) findViewById(R.id.ListItem_autoComplete);

    // adding listeners to button
    btnShare.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }
    });
    btnSort.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }
    });
    // setting adaptor to autoComplete TextView
//  adaptorAutoComplete = new ArrayAdapter<String>(mContext,android.R.layout.simple_dropdown_item_1line, listItems);
    txtAutoComplete.setThreshold(1);

    // adding Listener to Auto CompleteText View
    txtAutoComplete.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence charEnter, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            strItemName = charEnter.toString();
           new FetchItemListFromServer().execute();

        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        /*  strItemName = txtAutoComplete.getText().toString();
            new FetchItemListFromServer().execute();*/
            // adaptorAutoComplete.notifyDataSetChanged();
        }
    });
} // on create ends

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity__list_item, menu);
    return true;
} // method ends

public SoapObject getDataFromServer(String product_name, String store_id) {
    // all variables for Soap
    String SOAP_ACTION = "http://www.SupermarketAPI.com/COMMERCIAL_SearchForItem";
    String NAMESPACE = "http://www.SupermarketAPI.com";
    String METHOD_NAME = "COMMERCIAL_SearchForItem";
    String URL = "http://www.supermarketapi.com/api.asmx?WSDL";
    SoapObject objSoap = null;
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    // Use this to add parameters
    request.addProperty("APIKEY", "8b0e05b569");
    request.addProperty("ItemName",strItemName);
    request.addProperty("StoreID", "9829ae4237");
    // Declare the version of the SOAP request
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    envelope.dotNet = true;
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    // this is the actual part that will call the webservice
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        // Get the SoapResult from the envelope body.
        objSoap = (SoapObject) envelope.getResponse();
        if (objSoap != null) {
            String strData = objSoap.toString();
            System.out.println("envelop.getResponse//////"
                    + strData.toString());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return objSoap;
} // method ends

public class FetchItemListFromServer extends AsyncTask<Void, Void, Void> {
    SoapObject objSoap = null;

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        listItems.clear();
        objSoap = getDataFromServer(strItemName, "");
        if (objSoap != null) {
            System.out.println("getPropertyCountinevents//////////"
                    + objSoap.getPropertyCount());
            for (int i = 0; i < objSoap.getPropertyCount(); i++) {
                Object obj = objSoap.getProperty(i);
                if (obj instanceof SoapObject) {
                    SoapObject objNew = (SoapObject) obj;
                    listItems
                            .add(objNew.getProperty("Itemname").toString());
                }
            }
        }
        System.out.println("ArrayList size//////////"
                + listItems.size());
        runOnUiThread(new Runnable(){
            public void run(){
                adaptorAutoComplete = new ArrayAdapter<String>(mContext,android.R.layout.simple_dropdown_item_1line, listItems);


                 txtAutoComplete.setAdapter(adaptorAutoComplete);
                 adaptorAutoComplete.notifyDataSetChanged();
            }
        });
        return null;
    } // method ends


 } // asyntask class ends
 } // final class ends
4

3 回答 3

1

这是我的朋友 pskink 建议的可行解决方案

public class TestActivity extends Activity {
    public Context mContext;
    // views declaration
    public AutoCompleteTextView txtAutoComplete;
    public ListView lvItems;
    // arrayList for Adaptor
    ArrayList<String> listItems;
    // getting input from AutocompleteTxt
    String strItemName;
    // making Adaptor for autocompleteTextView
    ArrayAdapter<String> adaptorAutoComplete;
    private static final int ADDRESS_TRESHOLD = 2;
    private Filter filter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // for showing full screen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_listitem);
        mContext = this;
        listItems = new ArrayList<String>();
        // Declaring and getting all views objects
        Button btnShare = (Button) findViewById(R.id.ListItem_btnShare);
        Button btnSort = (Button) findViewById(R.id.ListItem_btnSort);
        lvItems = (ListView) findViewById(R.id.ListItem_lvItem);
        txtAutoComplete = (AutoCompleteTextView) findViewById(R.id.ListItem_autoComplete);

        // adding listeners to button
        btnShare.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

            }
        });
        btnSort.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

            }
        });

        String[] from = { "name" };
        int[] to = { android.R.id.text1 };
        SimpleCursorAdapter a = new SimpleCursorAdapter(this,
                android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
        a.setStringConversionColumn(1);
        FilterQueryProvider provider = new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence constraint) {
                // run in the background thread
                if (constraint == null) {
                    return null;
                }
                String[] columnNames = { Columns._ID, "name" };
                MatrixCursor c = new MatrixCursor(columnNames);
                try {

                    // total code for implementing my way of auto complte

                    String SOAP_ACTION = "your action";
                    String NAMESPACE = "your name space";
                    String METHOD_NAME = "your method name";
                    String URL = "your Url";
                    SoapObject objSoap = null;
                    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                    // Use this to add parameters
                    request.addProperty("KEY", yourkey);
                    request.addProperty("Key", constraint);
                    request.addProperty("Key", Id);
                    // Declare the version of the SOAP request
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                            SoapEnvelope.VER11);
                    envelope.setOutputSoapObject(request);
                    envelope.dotNet = true;

                    HttpTransportSE androidHttpTransport = new HttpTransportSE(
                            URL);

                    // this is the actual part that will call the webservice

                    androidHttpTransport.call(SOAP_ACTION, envelope);
                    // Get the SoapResult from the envelope body.
                    objSoap = (SoapObject) envelope.getResponse();
                    if (objSoap != null) {
                        String strData = objSoap.toString();

                    }

                    if (objSoap != null) {
                        System.out.println("getPropertyCountinevents//////////"
                                + objSoap.getPropertyCount());
                        for (int i = 0; i < objSoap.getPropertyCount(); i++) {
                            Object obj = objSoap.getProperty(i);
                            if (obj instanceof SoapObject) {
                                SoapObject objNew = (SoapObject) obj;

                                c.newRow()
                                        .add(i)
                                        .add(objNew.getProperty("Itemname")
                                                .toString());
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return c;
            }
        };
        a.setFilterQueryProvider(provider);
        txtAutoComplete.setAdapter(a);

    } // on create ends

} // final class ends
于 2013-11-15T11:39:04.293 回答
1

你可以像这样使用 asynytask

public class GetLocations extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            // getting GPS status
            isGPSEnabled = manager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = manager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (isGPSEnabled) {
                /*
                 * Criteria criteria = new Criteria(); String bestProvider =
                 * manager.getBestProvider(criteria, false); Location location =
                 * manager.getLastKnownLocation(bestProvider); double lat
                 * =location.getLatitude(); double longi
                 * =location.getLongitude();
                 * System.out.println("getting location continous ////// Lattti "
                 * +location.getLatitude() );
                 * System.out.println("getting location continous ////// LONGITU "
                 * + location.getLongitude());
                 */
                manager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 3000, 0, mylistener);

            } else {
                Toast.makeText(MyService.this, "Please oN Gps ",
                        Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            // getting current lattitude and longitude

            return null;
        }
    }
于 2013-12-11T07:28:01.653 回答
0

您可以在 AsyncTask 的 preExecute() 方法中设置一个全局布尔值。并在设置布尔值后取消先前的 AsynTask(即如果 AsyncTask 已经运行)。而已。

AsyncTask的使用请参考http://developer.android.com/reference/android/os/AsyncTask.html

于 2014-05-03T14:27:01.880 回答