【问题标题】:Searching with EditText使用 EditText 搜索
【发布时间】:2014-09-23 22:51:01
【问题描述】:

你能帮我解决这个问题吗?我想使用editText为我的列表视图创建一个搜索。一切都很好,但是当我运行应用程序时,它会导致运行时错误,并且我在 AlbumActivity.onTextChanged 上得到 NullPointerException。知道如何解决这个问题吗?谢谢。代码如下:

@SuppressLint("NewApi")
public class AlbumsActivity extends ListActivity{
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> albumsList;

JSONArray albums = null;    
EditText inputSearch;   
ArrayAdapter<String> adapter = null;    

private static final String URL_ALBUMS = "http://api.androidhive.info/songs/album.php";

private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SONGS_COUNT = "songs_count";

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

    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
    getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    cd = new ConnectionDetector(getApplicationContext());


    if (!cd.isConnectingToInternet()) {

        alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);

        return;
    }


    albumsList = new ArrayList<HashMap<String, String>>();
     inputSearch = (EditText) findViewById(R.id.inputSearch);

        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

                AlbumsActivity.this.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 LoadAlbums().execute();


ListView lv = getListView();


    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                long arg3) {


            Intent i = new Intent(getApplicationContext(), TrackListActivity.class);


            String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
            i.putExtra("album_id", album_id);               

            startActivity(i);
        }
    });     
}


class LoadAlbums extends AsyncTask<String, String, String> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AlbumsActivity.this);
        pDialog.setMessage("Listing Albums ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }


    protected String doInBackground(String... args) {

        List<NameValuePair> params = new ArrayList<NameValuePair>();


        String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
                params);


        Log.d("Albums JSON: ", "> " + json);

        try {               
            albums = new JSONArray(json);

            if (albums != null) {

                for (int i = 0; i < albums.length(); i++) {
                    JSONObject c = albums.getJSONObject(i);


                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String songs_count = c.getString(TAG_SONGS_COUNT);


                    HashMap<String, String> map = new HashMap<String, String>();


                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_SONGS_COUNT, songs_count);


                    albumsList.add(map);
                }
            }else{
                Log.d("Albums: ", "null");
            }

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

        return null;
    }

    protected void onPostExecute(String file_url) {

        pDialog.dismiss();

        runOnUiThread(new Runnable() {
            public void run() {

                ListAdapter adapter = new SimpleAdapter(
                        AlbumsActivity.this, albumsList,
                        R.layout.list_item_albums, new String[] { TAG_ID,
                                TAG_NAME, TAG_SONGS_COUNT }, new int[] {
                                R.id.album_id, R.id.album_name, R.id.songs_count });


                setListAdapter(adapter);
            }
        });

    }

}

}

【问题讨论】:

  • 你确定 - activity_albums.xml 包含 inputSearch 类型的 EditText 吗?
  • @Ved Prakash 是的,它包含 ediText,id 为 inputSEarch。当我开始输入要搜索的内容时,它在运行时出现错误
  • 检查您为onTextChanged 传递的所有值,并确保它们不为空。
  • @Ved Prakash 我猜我传递的值是空的。我不知道如何解决这个问题
  • 看看这篇文章 - stackoverflow.com/questions/16851134/…。查看适配器在onPostExecute() 中是如何初始化的,以及列表适配器是如何设置的。你必须这样做。

标签: android nullpointerexception android-edittext


【解决方案1】:

您的适配器未初始化。您拨打以下电话:

AlbumsActivity.this.adapter.getFilter().filter(cs.toString());  

这不起作用,因为您的适配器为空。你在onPostExecute 中调用setListAdapter 但这是ListActivity 的一个使用内部适配器的方法,它不会初始化你自己的成员变量。

相反,您可以在 onPostExecute 中执行此操作:

AlbumsActivity.this.adapter = new SimpleAdapter(AlbumsActivity.this, albumsList, R.layout.list_item_albums, new String[] { TAG_ID, TAG_NAME, TAG_SONGS_COUNT }, new int[] {R.id.album_id, R.id.album_name, R.id.songs_count });
// updating listview
setListAdapter(AlbumsActivity.this.adapter);

【讨论】:

  • 它有一个错误 - 类型不匹配:无法从 SimpleAdapter 转换为 ArrayAdapter
  • 将适配器的类型更改为 SimpleAdapter,而不是 ArrayAdapter;
  • 感谢它的工作。但如果我输入一个数字或数字。它复制了正在搜索的项目。这是为什么呢?
  • 我不知道。 “它复制了项目”是什么意思?
  • 我使用了一个数字进行搜索,因为有些项目在列表中的标题上有数字,但它会显示两个或三个具有相同值的项目结果。
猜你喜欢
  • 1970-01-01
  • 2012-06-04
  • 2017-11-21
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
相关资源
最近更新 更多