当前位置: 首页 > 知识库问答 >
问题:

无法在listview中设置数据进行搜索

茅星雨
2023-03-14

我正在根据edittext中的数据对listview数据进行搜索,我的代码对于搜索功能是正确的,但是有一个问题,只有当我在edittext中输入数据进行搜索时,listview上的数据才会出现,但是我想在搜索之前显示listview中的所有数据。

这是我的代码。

public class IndexBar extends Activity implements OnItemClickListener {

    HashMap<Character, Integer> alphabetToIndex;
    static String TAG = "IndexBar";
    int number_of_alphabets = -1;
    static IndexBarHandler handler;
    private EditText editsearch;
    @SuppressWarnings("unused")
    public IndexBar activity;
    private ArrayAdapter<String> adapter1;
    public ArrayAdapter<String> mainadapter;
    public ArrayList<String> memberlist;
    public ArrayList<String> first;
    public String[] member;
    public String firstname;
    public String search;
    ImageView imgFooterHome, imgFooterMagazine, imgFooterNews,
            imgFooterClients, imgFooterAboutUs;
    CustomListView mainlistview;
    ImageButton back;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.indexbarlayout);
        editsearch = (EditText) findViewById(R.id.textview_header);
        imgFooterHome = (ImageView) findViewById(R.id.imbMemberHome);
        imgFooterMagazine = (ImageView) findViewById(R.id.imbMemberMagazine);
        imgFooterNews = (ImageView) findViewById(R.id.imbMembernews);
        imgFooterClients = (ImageView) findViewById(R.id.imbMemberClient);
        imgFooterAboutUs = (ImageView) findViewById(R.id.imbMemberAboutUs);
        back = (ImageButton) findViewById(R.id.imgbtnMemberBack);
         mainlistview = (CustomListView) findViewById(R.id.listView_main);

        editsearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub
                //mainadapter.getFilter().filter(s.toString());
            }

            @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
                search = editsearch.getText().toString();
                memberlist = new ArrayList<String>();
                getAllMember();
                if (memberlist.size() > 0) {
                    mainadapter = new ArrayAdapter<String>(activity,
                            android.R.layout.simple_dropdown_item_1line,
                            memberlist);
                    mainlistview.setAdapter(mainadapter);
                }
            }
        });

        imgFooterAboutUs.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i = new Intent(IndexBar.this, AboutUsActivity.class);
                startActivity(i);
            }
        });
        imgFooterMagazine.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(IndexBar.this, MainActivity.class);
                startActivity(i);

            }
        });
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        imgFooterNews.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(IndexBar.this, NewsActivity.class);
                startActivity(i);
            }
        });

        imgFooterHome.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(IndexBar.this, GridViewActivity.class);
                startActivity(i);
            }
        });
        getScreenHeight(this);
        getScreenWidth(this);
        handler = new IndexBarHandler(this);

    }

//  protected void onResume() {
//      super.onResume();
//      memberlist = new ArrayList<String>();
//      /* populating the base listview */
//      CustomListView mainlistview = (CustomListView) findViewById(R.id.listView_main);
//      //Log.d("value of listview in onResume ", memberlist.toString());
//      String main_list_array[] = getResources().getStringArray(
//              R.array.base_array);
//      if (main_list_array == null) {
//          Log.d(TAG, "Array of the main listview is null");
//          return;
//      }
//      getAllMember();
//      mainadapter = new ArrayAdapter<String>(activity,
//              android.R.layout.simple_dropdown_item_1line,
//              memberlist);
//      mainlistview.setAdapter(mainadapter);
//      populateHashMap();
//
//  }

    public int convertDipToPx(int dp, Context context) { // 10dp=15px
        Resources r = context.getResources();
        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                r.getDisplayMetrics());
        return (int) px;
    }

    public int convertPxtoDip(int pixel) { // 15px=23dp
        float scale = getResources().getDisplayMetrics().density;
        int dips = (int) ((pixel / scale) + 0.5f);
        return dips;
    }

    /**
     * Determines the width of the screen in pixels
     * 
     * @return width
     */
    public int getScreenWidth(Activity activity) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        Log.d(TAG, "Screen Width in pixels=" + width);
        return width;
    }

    /**
     * Determines the height of the screen in pixels
     * 
     * @return height
     */
    public int getScreenHeight(Activity activity) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        int height = display.getHeight();
        Log.d(TAG, "Screen Height in pixels=" + height);
        return height;
    }

    public float pixelsToSp(Context context, Float px) {
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        Log.d(TAG, "GetTextSize in pixels=" + px + " In Sp="
                + (px / scaledDensity));
        return px / scaledDensity;
    }

    public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {

        if (!(view instanceof TextView || view == null))
            return;
        TextView rowview = (TextView) view;

        CharSequence alpahbet = rowview.getText();

        if (alpahbet == null || alpahbet.equals(""))
            return;

        String selected_alpahbet = alpahbet.toString().trim();
        Integer position = alphabetToIndex.get(selected_alpahbet.charAt(0));
        Log.d(TAG, "Selected Alphabet is:" + selected_alpahbet
                + "   position is:" + position);

        ListView listview = (ListView) findViewById(R.id.listView_main);
        listview.setSelection(position);
    }

    /**
     * This populates the HashMap which contains the mapping between the
     * alphabets and their relative position index.
     */
    private void populateHashMap() {
        alphabetToIndex = new HashMap<Character, Integer>();
        String base_list[] = getResources().getStringArray(R.array.base_array);
        int base_list_length = base_list.length;

        for (int i = 0; i < base_list_length; i++) {
            char firstCharacter = base_list[i].charAt(0);
            boolean presentOrNot = alphabetToIndex.containsKey(firstCharacter);
            if (!presentOrNot) {
                alphabetToIndex.put(firstCharacter, i);
                // Log.d(TAG,"Character="+firstCharacter+"  position="+i);
            }
        }
        number_of_alphabets = alphabetToIndex.size(); // Number of enteries in

        String alphabets[] = getResources().getStringArray(
                R.array.alphabtes_array);
        int index = -1;

        for (String alpha1 : alphabets) {
            char alpha = alpha1.charAt(0);
            index++;
            if (alphabetToIndex.containsKey(alpha))
                continue;
            for (int i = index + 1; i < 26; i++) { // start from next character
                // to last character
                char searchAlphabet = alphabets[i].charAt(0);
                if (alphabetToIndex.containsKey(searchAlphabet)) {
                    alphabetToIndex.put(alpha,
                            alphabetToIndex.get(searchAlphabet));
                    break;
                } else if (i == 25) 
                    alphabetToIndex.put(alpha, base_list_length - 1);
                else
                    continue;

            }//
        }//
    }

    public void getAllMember() {

        new AsyncTask<Void, Void, String>() {
            ProgressDialog mProgressDialog;
            public String firstname;

            protected void onPostExecute(String result) {
                mProgressDialog.dismiss();
                memberlist = new ArrayList<String>();
                first = new ArrayList<String>();

                try {
                    JSONObject jsob = new JSONObject(result.toString());
                    if (jsob.getString("msg").equalsIgnoreCase("Success")) {
                        JSONArray datajson = jsob.getJSONArray("data");
                        for (int i = 0; i < datajson.length(); i++) {

                            JSONObject c = datajson.getJSONObject(i);
                            firstname = c.getString("vUsername");
                            Log.d("firstname val", firstname);

                            memberlist.add(firstname);

                        }
                        if (datajson.length() > 0) {
                            mainadapter = new ArrayAdapter<String>(
                                 activity,
                                    android.R.layout.simple_dropdown_item_1line,
                                    memberlist);
                            mainlistview.setAdapter(mainadapter);

                        } else {
                            System.out.println("data eorr");
                        }
                    } 

                } catch (Exception e) {
                    Log.e("login problem", "" + e);

                }

            }

            private void startActivity(Intent i) {
                // TODO Auto-generated method stub

            }

            @Override
            protected String doInBackground(Void... arg0) {
                // Creating service handler class instance
                try {
                    HttpPost httppost1 = null;
                    HttpClient httpclient1 = new DefaultHttpClient();

                    httppost1 = new HttpPost(JsonKey.MAIN_URL);

                    // Add your data
                    List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(
                            2);
                    nameValuePairs1.add(new BasicNameValuePair("action",
                            "SearchMemberByKeyword"));
                    nameValuePairs1.add(new BasicNameValuePair(
                            "search_membername", search));
                    httppost1.setEntity(new UrlEncodedFormEntity(
                            nameValuePairs1));
                    // Execute HTTP Post Request
                    HttpResponse response1 = httpclient1.execute(httppost1);
                    BufferedReader in1 = new BufferedReader(
                            new InputStreamReader(response1.getEntity()
                                    .getContent()));
                    StringBuffer sb1 = new StringBuffer("");
                    String line1 = "";
                    while ((line1 = in1.readLine()) != null) {
                        sb1.append(line1);
                    }
                    in1.close();
                    Log.e(" Get All magazine original data", sb1.toString());
                    return sb1.toString();
                } catch (Exception e) {
                    Log.e("Get All magazine response problem", "" + e);
                    return " ";
                }
            }

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                mProgressDialog = new ProgressDialog(IndexBar.this);
                mProgressDialog.setTitle("");
                mProgressDialog.setCanceledOnTouchOutside(false);
                mProgressDialog.setMessage("Please Wait...");
                mProgressDialog.show();

            }
        }.execute();

    }
}

logcat:01-30 17:33:23.926:E/AndroidRuntime(782):在android上。应用程序。活动线程。handleLaunchActivity(ActivityThread.java:2084)01-30 17:33:23.926:E/AndroidRuntime(782):在android上。应用程序。活动线程。在android上访问$600(ActivityThread.java:130)01-30 17:33:23.926:E/AndroidRuntime(782)。应用程序。ActivityThread$H.handleMessage(ActivityThread.java:1195)01-30 17:33:23.926:E/AndroidRuntime(782):在android上。操作系统。汉德勒。dispatchMessage(Handler.java:99)01-30 17:33:23.926:E/AndroidRuntime(782):在android上。操作系统。活套。loop(Looper.java:137)01-30 17:33:23.926:E/AndroidRuntime(782):在android上。应用程序。活动线程。main(ActivityThread.java:4745)01-30 17:33:23.926:E/AndroidRuntime(782):在java。朗,反思一下。方法Invokenactive(本机方法)01-30 17:33:23.926:E/AndroidRuntime(782):在java。朗,反思一下。方法invoke(Method.java:511)01-30 17:33:23.926:E/AndroidRuntime(782):在com上。Android内部的操作系统。ZygoteInit$MethodandArgscaler。运行(zyteinit.java:786)01-30 17:33:23.926:E/AndroidRuntime(782):在com上。Android内部的操作系统。合子体。main(zyteinit.java:553)01-30 17:33:23.926:E/AndroidRuntime(782):在dalvik。系统原生艺术。main(原生方法)01-30 17:33:23.926:E/AndroidRuntime(782):由java引起。lang.NullPointerException 01-30 17:33:23.926:E/AndroidRuntime(782):在android上。小装置。ArrayAdapter。init(ArrayAdapter.java:310)01-30 17:33:23.926:E/AndroidRuntime(782):在android上。小装置。ArrayAdapter。(ArrayAdapter.java:153)01-30 17:33:23.926:E/AndroidRuntime(782):在com上。实例ncpa。IndexBar。android:723.android:723。应用程序。活动performCreate(Activity.java:5008)01-30 17:33:23.926:E/AndroidRuntime(782):在android上。应用程序。仪器仪表。callActivityOnCreate(Instrumentation.java:1079)01-30 17:33:23.926:E/AndroidRuntime(782):在android上。应用程序。活动线程。performLaunchActivity(ActivityThread.java:2023)

共有1个答案

程赞
2023-03-14

首先设置下面的代码,然后在edittext-aftertextchanged方法中调用notifydatasetchanged方法。

 mainadapter = new ArrayAdapter<String>(activity,
                        android.R.layout.simple_dropdown_item_1line,
                        memberlist);
                mainlistview.setAdapter(mainadapter);
 类似资料:
  • 问题内容: 当我从数据库中检索数据时,我碰壁了。我设法将列名放入我的表中,这可以正常工作并且应该工作。 当我尝试添加行时发芽,我发现没有数据添加到我的tableview中,我试图从代表单个行的字符串数组中添加行。我不知道用户会用他的查询请求多少列以及如何大表是这样,所以我不能创建行对象和代表每一列的所有属性。 问题 是如何用从数据库中成功检索到的行填充String表中的行,并以String []的

  • 我使用以下代码创建了一个数据表:- 主要的php-它包含调用数据表的脚本和从sql数据库获取数据的php脚本 和dtServerSideBasicScript。php-它是从sql server获取数据的脚本:- 现在,我必须应用数据表上方的Advanced filter部分,它可以是由以下字段组成的表单-姓名输入、年龄范围输入和性别选择输入字段。提交此表格时,相关搜索结果应显示在数据表中。

  • 我在学习PHP,我创建了一个页面来用MySQL显示我的数据表。我想用这些数据进行分页、搜索和排序。 我写了一些条件来搜索和排序。但它不起作用。我的传呼似乎工作得很好。 当我运行它时,它说:警告:mysqli_fetch_array()期望参数1是mysqli_result。你能帮助我吗?非常感谢。

  • 如何在扩展ListView的另一个片段中将ArrayList数据设置到ListView中? 我们将非常感谢各位专家的帮助。 自定义ArrayList接受int、string、string。我从两个EditText获取用户输入并将它们添加到此ArrayList。当用户重新输入时,它应该继续将其添加到ArrayList。 目标是从用户那里获取所有条目,并在下一个片段的ListView中显示它。但只有两

  • 如何动态设置数据源?像下面的Spring: 我可以从Spring导入这个功能到Java的EE 7企业应用程序吗?

  • 我试图存储以前播放过的歌曲的uri,使用share d首选项。但是当为了播放歌曲而获取和重建uri时,我会收到以下错误消息: 05-03 20:43:14.642 8617-8716/com.stopwatch.appW/MediaPlayer:无法在客户端打开文件;尝试服务器端:java.lang.安全异常:权限拒绝:打开提供程序com.android.providers.media.Media