0

我有下一个代码可以在 Spotify 服务器上搜索艺术家和歌曲。我有一个自动完成文本,但我的问题是,如果我搜索某些内容,例如“David Guetta”,并且每次删除一个字符时我都会尝试用退格键(<--)删除它会进行搜索,如果我这样做的速度如此之快应用程序崩溃(大量使用?)。我真的不知道是不是为了这个问题。

我能做些什么来解决这个问题?通过等待时间来搜索它可以修复,但我不知道该怎么做。

你能帮我解决这个问题吗?谢谢你。

这是我的 SearchMusic.java 代码。

public class SearchMusic extends Activity {

    AutoCompleteTextView autoCompleteSongs;
    String searchTerms;
    String[] arrayArtist = new String[64];
    String[] arrayTrack = new String[64];
    ArrayAdapter<String> adapter;
    List<String> songs;
    List<String> lArtist;
    List<String> lTrack;

    boolean bothsearchs = false; // Controlamos que haya busqueda por artista y
                                    // pista si uno no existe.

    int nArtist = 0; // iterator

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_music);

        autoCompleteSongs = (AutoCompleteTextView) findViewById(R.id.autoCompletePetition);
        final ArrayAdapter<String> list = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line);

        // autoCompleteSongs.setThreshold(1);
        // autoCompleteSongs.addTextChangedListener(this);
        // autoCompleteSongs.setAdapter(new
        // ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,
        // item));

        autoCompleteSongs.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                if (s.length() > 3) {
                    searchTerms = s.toString();
                    searchTerms = searchTerms.replace(" ", "+");
                    // Buscamos por artista
                    AsyncHttpClient client = new AsyncHttpClient();
                    client.get("http://ws.spotify.com/search/1/artist.json?q="
                            + searchTerms + "*", null,
                            new JsonHttpResponseHandler() {
                                public void onSuccess(JSONObject data) {
                                    try {
                                        // Hay artistas con ese nombre
                                        if (data.length() > 0) {
                                            JSONArray artist = new JSONArray(
                                                    data.getJSONArray("artists")
                                                            .toString());

                                            for (int i = 0; i < 6; i++) {

                                                JSONObject orden = artist
                                                        .getJSONObject(i);
                                                String name = orden
                                                        .getString("name");
                                                list.add(name);
                                                arrayArtist[i] = name;
                                                arrayTrack[i] = "";
                                                nArtist++;
                                            }
                                        } else {
                                            bothsearchs = true;
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }

                                @Override
                                public void onFailure(Throwable arg0) {

                                }
                            });

                    // Buscamos por pista
                    client.get("http://ws.spotify.com/search/1/track.json?q="
                            + searchTerms + "*", null,
                            new JsonHttpResponseHandler() {
                                public void onSuccess(JSONObject spoty) {
                                    try {
                                        JSONArray artist = new JSONArray(spoty
                                                .getJSONArray("tracks")
                                                .toString());

                                        for (int i = nArtist; i < nArtist + 6 ; i++) {
                                            JSONObject orden = artist
                                                    .getJSONObject(i);
                                            String name = orden
                                                    .getString("name");
                                            JSONArray nameArtist = new JSONArray(
                                                    orden.getJSONArray(
                                                            "artists")
                                                            .toString());
                                            JSONObject namArt = nameArtist
                                                    .getJSONObject(0);
                                            String nameArt = namArt
                                                    .getString("name");

                                            list.add("[" + nameArt + "] "
                                                    + name);
                                            arrayArtist[i] = nameArt;
                                            arrayTrack[i] = name;
                                        }

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onFailure(Throwable arg0) {
                                }

                            });

                    list.notifyDataSetChanged();
                    TextView text = (TextView) findViewById(R.id.petitionTextView);

                    for(int i = 0; i < 12; i++){
                        Log.i("AART", "" + arrayArtist[i]);
                        Log.i("ATRA", "" + arrayTrack[i]);
                        }

                    if(arrayArtist[0] == null && arrayTrack[0] == ""){
                        text.setText("No hay resultados");
                    }else{

                        for(int i = 0; i < 12; i++){
                            String register = "<font color=#64c7eb>" + arrayArtist[i] + "</font> <font color=#272527>" + arrayTrack[i] + "</font></br>";
                            text.setText(Html.fromHtml(register));
                        }
                    }
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

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

    }

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

}

如果我是对的,这就是我需要的代码。问题是如何阻止它。¬¬

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
4

3 回答 3

0

当我使用 GooglePlaceApi 获取地址列表时,我遇到了同样的问题。我在 performFiltering()、publishResults() 以及其余调用的方法中使用了同步。它对我有用。也许你可以试一试。

 synchronized (input)
  {
   // Do something inside
  }
于 2013-11-13T15:51:09.837 回答
0

我认为你已经给出了一个很好的解决方案。尝试将 http 请求包装在 TimerTask 中,并创建一个计时器机制来取消 TimerTask。

示例(未测试):

public class SearchMusic extends Activity {

    AutoCompleteTextView autoCompleteSongs;
    String searchTerms;
    String[] arrayArtist = new String[64];
    String[] arrayTrack = new String[64];
    ArrayAdapter<String> adapter;
    List<String> songs;
    List<String> lArtist;
    List<String> lTrack;
    //Declare and initialize the timer
    Timer t = new Timer();

    boolean bothsearchs = false; // Controlamos que haya busqueda por artista y
                                    // pista si uno no existe.

    int nArtist = 0; // iterator

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_music);

        autoCompleteSongs = (AutoCompleteTextView) findViewById(R.id.autoCompletePetition);
        final ArrayAdapter<String> list = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line);

        // autoCompleteSongs.setThreshold(1);
        // autoCompleteSongs.addTextChangedListener(this);
        // autoCompleteSongs.setAdapter(new
        // ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,
        // item));

        autoCompleteSongs.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                if (s.length() > 3) {

                    // Cancel the Timer and all scheduled tasks
                    t.cancel();
                    t.purge();
                    t = new Timer();

                    //Set the schedule function and rate
                    t.schedule(new TimerTask() {

                        @Override
                        public void run() 
                        {
                            //Called each time when 1000 milliseconds (1 second) (the period parameter)
                            searchTerms = s.toString();
                            searchTerms = searchTerms.replace(" ", "+");
                            // Buscamos por artista
                            AsyncHttpClient client = new AsyncHttpClient();
                            client.get("http://ws.spotify.com/search/1/artist.json?q="
                                    + searchTerms + "*", null,
                                    new JsonHttpResponseHandler() {
                                        public void onSuccess(JSONObject data) {
                                            try {
                                                // Hay artistas con ese nombre
                                                if (data.length() > 0) {
                                                    JSONArray artist = new JSONArray(
                                                            data.getJSONArray("artists")
                                                                    .toString());

                                                    for (int i = 0; i < 6; i++) {

                                                        JSONObject orden = artist
                                                                .getJSONObject(i);
                                                        String name = orden
                                                                .getString("name");
                                                        list.add(name);
                                                        arrayArtist[i] = name;
                                                        arrayTrack[i] = "";
                                                        nArtist++;
                                                    }
                                                } else {
                                                    bothsearchs = true;
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }

                                        }

                                        @Override
                                        public void onFailure(Throwable arg0) {

                                        }
                                    });

                            // Buscamos por pista
                            client.get("http://ws.spotify.com/search/1/track.json?q="
                                    + searchTerms + "*", null,
                                    new JsonHttpResponseHandler() {
                                        public void onSuccess(JSONObject spoty) {
                                            try {
                                                JSONArray artist = new JSONArray(spoty
                                                        .getJSONArray("tracks")
                                                        .toString());

                                                for (int i = nArtist; i < nArtist + 6 ; i++) {
                                                    JSONObject orden = artist
                                                            .getJSONObject(i);
                                                    String name = orden
                                                            .getString("name");
                                                    JSONArray nameArtist = new JSONArray(
                                                            orden.getJSONArray(
                                                                    "artists")
                                                                    .toString());
                                                    JSONObject namArt = nameArtist
                                                            .getJSONObject(0);
                                                    String nameArt = namArt
                                                            .getString("name");

                                                    list.add("[" + nameArt + "] "
                                                            + name);
                                                    arrayArtist[i] = nameArt;
                                                    arrayTrack[i] = name;
                                                }

                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }

                                        @Override
                                        public void onFailure(Throwable arg0) {
                                        }

                                    });

                            list.notifyDataSetChanged();
                            TextView text = (TextView) findViewById(R.id.petitionTextView);

                            for(int i = 0; i < 12; i++){
                                Log.i("AART", "" + arrayArtist[i]);
                                Log.i("ATRA", "" + arrayTrack[i]);
                                }

                            if(arrayArtist[0] == null && arrayTrack[0] == ""){
                                text.setText("No hay resultados");
                            }else{

                                for(int i = 0; i < 12; i++){
                                    String register = "<font color=#64c7eb>" + arrayArtist[i] + "</font> <font color=#272527>" + arrayTrack[i] + "</font></br>";
                                    text.setText(Html.fromHtml(register));
                                }
                            }
                        }

                    },
                    //Set how long before to start calling the TimerTask (in milliseconds)
                    0,
                    //Set the amount of time between each execution (in milliseconds)
                    1000);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

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

    }

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

}
于 2013-06-03T14:23:12.430 回答
0

您可以做的最好的事情是使用处理程序,这是一个带有按钮的简单示例。但是该按钮代表代码上的退格键。

这个想法是在 500 毫秒内安排搜索操作,但是当有人再次点击搜索按钮时,我们会重新安排搜索操作,直到用户停止点击搜索按钮。

祝你好运!

   public class MyActivity extends Activity implements OnClickListener
    {
        protected static final int MSG_SEARCH = 0;

        protected Button buttonSearch;

        protected Handler handler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                switch (msg.what)
                {
                    case MSG_SEARCH:

                        MyActivity.this.search();
                        break;
                }
            }
        };

        @Override
        public void onClick(View inView)
        {
            if (inView == this.buttonSearch)
            {
                this.handler.removeMessages(MSG_SEARCH);
                final Message message = Message.obtain(this.handler, MSG_SEARCH);
                this.handler.sendMessageDelayed(message, 500);
            }
        }

        protected void search()
        {
            // your seach code
        }
    }
于 2013-06-04T08:31:34.770 回答