简体   繁体   English

避免列表中的重复项

[英]Avoid duplicates in list

I am trying to avoid duplicate values in my list but it's not working.我试图避免列表中出现重复值,但它不起作用。 Can you help me for this?你能帮我解决这个问题吗? I did a lot of work on it, but I'm new to android and also coding.我做了很多工作,但我是 android 和编码的新手。 Can you help me where I have made my mistake?你能帮我在哪里犯错吗?

import java.util.ArrayList;

public class Dynamic extends Activity {

    Button bt, bt2, ent, clr;
    EditText et, et2;
    String input, input1;
    public static ArrayList<String> k_listItems = new ArrayList<String>();
    public static ArrayList<String> p_listItems = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.nameok);
        et = (EditText) findViewById(R.id.name);

        input = et.getText().toString();

        bt.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                if (et.getText().length() == 0) {
                    Context context = getApplicationContext();
                    CharSequence text = "Enter Your Name";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                } else {

                    {
                        for (int i = 0; i < k_listItems.size(); i++) {
                            if (k_listItems.get(i).equals("input")) {
                                Intent in = new Intent(Dynamic.this, Dynamic.class);
                                startActivity(in);
                                Toast.makeText(getApplicationContext(), "Name Already Exists", Toast.LENGTH_SHORT).show();
                                break;
                            }
                        }
                    }

                    if (et.getText().length() == 0) {
                        Context context = getApplicationContext();
                        CharSequence text = "Enter Your Number";
                        int duration = Toast.LENGTH_SHORT;
                        Toast toast = Toast.makeText(context, text, duration);
                        toast.show();
                    } else {

                        et2.setVisibility(View.VISIBLE);
                        bt2.setVisibility(View.VISIBLE);
                        bt2.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                if (et2.getText().length() == 0) {
                                    Context context = getApplicationContext();
                                    CharSequence text = "Enter Your Number";
                                    int duration = Toast.LENGTH_SHORT;
                                    Toast toast = Toast.makeText(context, text, duration);
                                    toast.show();
                                } else {
                                    ent.setVisibility(View.VISIBLE);
                                    clr.setVisibility(View.VISIBLE);
                                    ent.setOnClickListener(new View.OnClickListener() {

                                        @Override
                                        public void onClick(View v) {
                                            if (null != input && input.length() > 0) {
                                                k_listItems.add(input);
                                            }
                                            if (null != input1 && input1.length() > 0) {
                                                p_listItems.add(input1);
                                            }
                                            input = et.getText().toString();
                                            input1 = et2.getText().toString();

                                            Intent in = new Intent(Dynamic.this, GetList.class);
                                            in.putExtra("input", input);
                                            in.putExtra("input1", input1);
                                            startActivity(in);
                                        }
                                    });
                                    clr.setOnClickListener(new View.OnClickListener() {

                                        @Override
                                        public void onClick(View v) {
                                            Intent in4 = new Intent(Dynamic.this, Dynamic.class);
                                            startActivity(in4);
                                        }
                                    });
                                }
                            }
                        });

                    }
                }
            }
        });
    }

    protected void onStart() {
        super.onStart();

        et2 = (EditText) findViewById(R.id.number);
        bt2 = (Button) findViewById(R.id.numberok);
        ent = (Button) findViewById(R.id.enter);
        clr = (Button) findViewById(R.id.clear);
    }

    public void onBackPressed() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

Mylist to get that list... Mylist 以获取该列表...

import java.util.ArrayList;


public class GetList extends Activity {

    ListView lv;
    Button bt3;
    Dialog d;
    EditText edt;
    String x;
    public static ArrayList<String> x_listItems = new ArrayList<String>();
    public static ArrayList<String> y_listItems = new ArrayList<String>();
    String inp, inp1;

    public static ArrayAdapter<String> a_adapter;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        lv = (ListView) findViewById(R.id.listView1);

        Intent in = getIntent();

        inp = in.getStringExtra("input");
        inp1 = in.getStringExtra("input1");

        a_adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, x_listItems);

        lv.setAdapter(a_adapter);

        if (null != inp && inp.length() > 0) {
            x_listItems.add(inp);
            a_adapter.notifyDataSetChanged();
        }
        if (null != inp1 && inp1.length() > 0) {
            y_listItems.add(inp1);
            Log.v("num", "" + y_listItems);
        }
        lv.setOnItemClickListener(new OnItemClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position,
                                    long arg3) {
                if (x_listItems.get(position) != null) {
                    AlertDialog ab = new AlertDialog.Builder(
                            GetList.this).create();
                    ab.setTitle("Details");
                    ab.setMessage("NAME:" + x_listItems.get(position) + "\n" + "Number" + y_listItems.get(position));
                    ab.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(getApplicationContext(), "Thanx for visiting", Toast.LENGTH_SHORT).show();
                        }
                    });
                    ab.show();
                }
            }
        });
        lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                                           final int position, long arg3) {
                if (x_listItems.get(position) != null) {
                    AlertDialog ab = new AlertDialog.Builder(
                            GetList.this).create();
                    ab.setTitle("Slect Your Option");
                    ab.setButton("Edit", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            final String z = x_listItems.get(position);
                            Log.v("position", "" + z);
                            d = new Dialog(GetList.this);
                            d.setContentView(R.layout.abc);
                            d.setTitle("Enter new name");
                            Button sub = (Button) d.findViewById(R.id.submit);
                            edt = (EditText) d.findViewById(R.id.edt);
                            edt.setText(x_listItems.get(position));

                            sub.setOnClickListener(new OnClickListener() {
                                public void onClick(View v) {
                                    x_listItems.remove(position);
                                    x = edt.getText().toString();
                                    x_listItems.add(position, x);
                                    String p = x_listItems.get(position);
                                    String f = y_listItems.get(position);
                                    y_listItems.set(position, f);
                                    Log.v("changednum", "" + inp1);
                                    a_adapter.notifyDataSetChanged();
                                    lv.setAdapter(a_adapter);
                                    Toast.makeText(getApplicationContext(), "" + edt.getText().toString().trim(), 4000).show();
                                    d.dismiss();
                                }
                            });
                            d.show();
                        }
                    });

                    ab.setButton2("Delete", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            x_listItems.remove(position);
                            y_listItems.remove(position);
                            a_adapter.notifyDataSetChanged();
                            lv.setAdapter(a_adapter);
                        }
                    });
                    ab.show();
                }
                return true;
            }

            private int get(int position) {
                return 0;
            }
        });
    }

    public void onBackPressed() {
        super.onBackPressed();
        Intent in4 = new Intent(GetList.this, Dynamic.class);
        startActivity(in4);
    }
}

Set will not allow duplicates...See example below 设置不允许重复...请参见下面的示例

 HashSet<String> x_hashSet = new HashSet<String>();
 HashSet<String> y_hashSet = new HashSet<String>();

 x_hashSet.addAll(x_listItems);
 y_hashSet.addAll(y_listItems);

 x_listItems.clear();
 y_listItems.clear();

 x_listItems.addAll(x_hashSet);
 y_listItems.addAll(y_hashSet);

Then add list to adapter. 然后将列表添加到适配器。 That's it. 而已。

Hope this will help you ;) 希望这个能对您有所帮助 ;)

Why don't you use a Set instead of a List ? 为什么不使用Set而不是List They do not allow duplicates. 他们不允许重复。 You will need a hashCode and equals method if you put your own objects in there, but it should just work for Strings 如果您将自己的对象放在其中,则将需要hashCode和equals方法,但它仅适用于字符串

HashSet does not allow duplicate values. HashSet不允许重复值。 It provides add method rather put method. 它提供了add方法而不是put方法。 You also use its contain method to check whether the object is already available in HashSet. 您还可以使用其包含方法来检查对象在HashSet中是否已经可用。 HashSet can be used where you want to maintain a unique list. HashSet可用于您要维护唯一列表的地方。

HashSet<String> stateSet = new HashSet<String>();
stateSet.add ("CA");
stateSet.add ("WI");
stateSet.add ("NY");

if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
     System.out.println("Already found");
else
    stateSet.add("PB");

The answer is far from question actuality but for such who still arise with it you can find the one of preffered technique with this link Java program to remove duplicate characters from a string .答案与实际问题相去甚远,但对于那些仍然出现问题的人,您可以通过此链接Java 程序找到首选技术之一,以从字符串中删除重复字符 The other point is efficiency but it is not part of this question.另一点是效率,但这不是这个问题的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM