【问题标题】:CheckBox Issues: item selection & SQLite Database - ANDROID复选框问题:项目选择和 SQLite 数据库 - ANDROID
【发布时间】:2012-09-06 06:33:05
【问题描述】:

我遇到了 CheckBox 问题。那么两个问题。

  1. 当我选中复选框中的项目时,其他项目也被选中。
  2. 我无法将名称(检查后)捕获到 SQLiteDatabase 表中。

我的应用有一个联系人姓名列表视图(从 android 内置联系人列表中检索)和复选框。另外,用户可以多选列表中的名称。
我在一节课中有两节课
1.public class ContactsList
2.public class MyCustomAdapter

这是我的代码: ContactsList.java - 更新了我的代码

公共类 ContactsList 扩展 ListActivity { static ArrayList friendsList = new ArrayList();

ListView list;
private ContactsList[] friends;
private ArrayAdapter<ContactsList> listAdapter;

final Context context = this;

Cursor cursor;

String[] buddiesList = 
    {"Kanak Priya",
    "Joanne Liew",
    "Michelle Lam",
    "Teo Kin Hua",
    "Melissa Haiting",
    "David Yeo",
    "Natasha Akhbar",
    "Gillian Gan",
    "Sonia",
    "Ms Long",
    "Joan Tang",
    "Stephanie",
    "Nur Ashiqin"
    };

BuddyDBAdapter buddyDB = new BuddyDBAdapter(this);

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    //setListAdapter(new MyCustomAdapter(ContactsList.this, R.layout.contacts_list, buddiesList));
    setContentView(R.layout.contacts_list);

    setListAdapter(new ArrayAdapter<String>(this, R.layout.contacts_list, buddiesList));

    ListView list = (ListView) findViewById(android.R.id.list);
    //ListView list = getListView();
    list.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id)
        {
            ContactsList friends = listAdapter.getItem(position);
            friends.**toggleChecked**();
            ContactsListViewHolder viewHolder = (ContactsListViewHolder) view.getTag();
            viewHolder.**getCheckBox**().setChecked(friends.**isChecked**());


            Cursor cursor = null;

               cursor = (Cursor) parent.getItemAtPosition(position);
               Intent intent = new Intent(ContactsList.this, Create_Events.class);
               intent.putExtra("name", cursor.getString(cursor.getColumnIndex(buddyDB.KEY_NAME)));
               startActivity(intent);

        }

    });

    ContactsList[] arrContacts = friendsList.toArray(new ContactsList[0]);


    Uri allContacts = Uri.parse("content://contacts/people");

    Cursor c = managedQuery(allContacts, null, null, null, null);

    String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
    int[] views = new int[]  {R.id.contactName};

    startManagingCursor(c);

    SimpleCursorAdapter friendsAdapter = new SimpleCursorAdapter(this, R.layout.contacts_list, c, columns, views);
    this.setListAdapter(friendsAdapter);
}

private static class ContactsName
{
    private String name = "";
    private boolean checked = false;

    public ContactsName(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }

    public boolean isChecked()
    {
        return checked;
    }

    public void setChecked(boolean checked)
    {
        this.checked = checked;
    }

    public String toString()
    {
        return name;
    }

    public void toggleChecked()
    {
        checked = !checked;
    }
}

private static class ContactsListViewHolder
{
    private CheckBox nameCheck;
    private TextView contactName;

    public ContactsListViewHolder(TextView contactName, CheckBox nameCheck)
    {
        this.nameCheck = nameCheck;
        this.contactName = contactName;
    }

    public CheckBox getNameCheck()
    {
        return nameCheck;
    }

    public TextView getContactName()
    {
        return contactName;
    }
}

private static class ContactsCustomAdapter extends ArrayAdapter<ContactsList>
{
    private LayoutInflater inflater;

    public ContactsCustomAdapter(Context context, List<ContactsList> friendsList)
    {
        **super(context, R.layout.contacts_list, R.id.contactName,  R.id.contactCheckbox, friendsList);**
        inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ContactsList friends = (ContactsList) this.getItem(position);

        CheckBox nameCheck;
        TextView contactName;

        if(convertView == null)
        {
            convertView = inflater.inflate(R.layout.contacts_list, null);

            contactName = (TextView) convertView.findViewById(R.id.contactName);
            nameCheck = (CheckBox) convertView.findViewById(R.id.contactCheckbox);

            convertView.setTag(new ContactsListViewHolder(contactName, nameCheck));

            nameCheck.setOnClickListener(new View.OnClickListener()
                {

                    @Override
                    public void onClick(View v)
                    {
                        CheckBox cb = (CheckBox) v;
                        ContactsList friends = (ContactsList) cb.getTag();
                        friends.**setChecked**(cb.isChecked());

                        if(cb.isChecked())
                        {
                            friendsList.add(friends.**name**);
                        }
                        else
                        {
                            friendsList.remove(friends.**name**);
                        }
                    }   
                });
        }
        else
        {
            ContactsListViewHolder viewHolder = (ContactsListViewHolder) convertView.getTag();
            nameCheck = viewHolder.**getCheckBox**();
            contactName = viewHolder.**getTexView**();
        }
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id)
{
    buddyDB.open();
    long name_id;
    super.onListItemClick(l, v, position, id);

    Cursor cursor = null;

       cursor = (Cursor) l.getItemAtPosition(position);
       Intent intent = new Intent(ContactsList.this, Create_Events.class);
       intent.putExtra("name", cursor.getString(cursor.getColumnIndex(buddyDB.KEY_NAME)));
       startActivity(intent);

    ListView list = getListView();
    list.setChoiceMode(2);
    list.setTextFilterEnabled(true);

    l.setItemChecked(position, l.isItemChecked(position));

    Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
    c.moveToPosition(position);

    TextView contactName = (TextView) v.findViewById(R.id.contactName);
    String NameValue = contactName.getText().toString();        
    name_id = buddyDB.insertNames(NameValue);

    Toast.makeText(getBaseContext(),
            "Selected: " + buddiesList[position], Toast.LENGTH_SHORT).show();       
    buddyDB.close();



}

}

注意
我加粗的代码意味着这些是我遇到的错误。它要求 isChecked(), toggleChecked(), setChecked() and getCheckBox() 的创建方法。

要求为name创建字段类型或常量类型,但我已经创建了它

private static class ContactsName
    {
        private String name = "";

我不确定我在哪里编码错误。我需要能够将名称插入数据库表中,并且我想确保当我检查一个名称时,不应该检查其他名称。谁能帮帮我?
谢谢! =)

【问题讨论】:

    标签: android listview checkbox insert sqlite


    【解决方案1】:

    这里以行星名称为例,只需将字符串更改为联系人名称:

    public class PlanetsActivity extends Activity {
    static ArrayList<String> FavList = new ArrayList<String>();
    
      private ListView mainListView ;
      private Planet[] planets ;
      private ArrayAdapter<Planet> listAdapter ;
    
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
    
        // Find the ListView resource. 
        mainListView = (ListView) findViewById( R.id.mainListView );
    
    // When item is tapped, toggle checked properties of CheckBox and Planet.
        mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick( AdapterView<?> parent, View item, 
                               int position, long id) {
        Planet planet = listAdapter.getItem( position );
        planet.toggleChecked();
        PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
        viewHolder.getCheckBox().setChecked( planet.isChecked() );
      }
    });
    
    
        // Create and populate planets.
    planets = (Planet[]) getLastNonConfigurationInstance() ;
    if ( planets == null ) {
      planets = new Planet[] { 
          new Planet("Mercury"), new Planet("Venus"), new Planet("Earth"), 
          new Planet("Mars"), new Planet("Jupiter"), new Planet("Saturn"), 
          new Planet("Uranus"), new Planet("Neptune"), new Planet("Ceres"),
          new Planet("Pluto"), new Planet("Haumea"), new Planet("Makemake"),
          new Planet("Eris")
          };  
        }
    ArrayList<Planet> planetList = new ArrayList<Planet>();
    planetList.addAll( Arrays.asList(planets) );
    
    // Set our custom array adapter as the ListView's adapter.
    listAdapter = new PlanetArrayAdapter(this, planetList);
    mainListView.setAdapter( listAdapter );      
      }
    
      /** Holds planet data. */
      private static class Planet {
      private String name = "" ;
      private boolean checked = false ;
      public Planet( String name ) {
      this.name = name ;
    }
    public String getName() {
      return name;
    }
    public boolean isChecked() {
      return checked;
    }
    public void setChecked(boolean checked) {
      this.checked = checked;
    }
    public String toString() {
      return name ; 
    }
    public void toggleChecked() {
      checked = !checked ;
        }
      }
    
      /** Holds child views for one row. */
      private static class PlanetViewHolder {
    private CheckBox checkBox ;
    private TextView textView ;
    public PlanetViewHolder( TextView textView, CheckBox checkBox ) {
      this.checkBox = checkBox ;
      this.textView = textView ;
    }
    public CheckBox getCheckBox() {
      return checkBox;
    }
    public TextView getTextView() {
      return textView;
    }    
      }
    
      /** Custom adapter for displaying an array of Planet objects. */
      private static class PlanetArrayAdapter extends ArrayAdapter<Planet> {
    
        private LayoutInflater inflater;
    
        public PlanetArrayAdapter( Context context, List<Planet> planetList ) {
          super( context, R.layout.simplerow, R.id.rowTextView, planetList );
          // Cache the LayoutInflate to avoid asking for a new one each time.
          inflater = LayoutInflater.from(context) ;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
          // Planet to display
          Planet planet = (Planet) this.getItem( position ); 
    
          // The child views in each row.
          CheckBox checkBox ; 
          TextView textView ; 
    
          // Create a new row view
          if ( convertView == null ) {
           convertView = inflater.inflate(R.layout.simplerow, null);
    
          // Find the child views.
          textView = (TextView) convertView.findViewById( R.id.rowTextView );
          checkBox = (CheckBox) convertView.findViewById( R.id.CheckBox01 );
    
        // Optimization: Tag the row with it's child views, so we don't have to 
        // call findViewById() later when we reuse the row.
        convertView.setTag( new PlanetViewHolder(textView,checkBox) );
    
        // If CheckBox is toggled, update the planet it is tagged with.
        checkBox.setOnClickListener( new View.OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) v ;
            Planet planet = (Planet) cb.getTag();
            planet.setChecked( cb.isChecked() );
    
            if (cb.isChecked()){
                FavList.add(planet.name);
            }
            else{
                FavList.remove(planet.name);
            }
          }
        });        
      }
      // Reuse existing row view
      else {
        // Because we use a ViewHolder, we avoid having to call findViewById().
        PlanetViewHolder viewHolder = (PlanetViewHolder) convertView.getTag();
        checkBox = viewHolder.getCheckBox() ;
        textView = viewHolder.getTextView() ;
      }
    
      // Tag the CheckBox with the Planet it is displaying, so that we can
      // access the planet in onClick() when the CheckBox is toggled.
      checkBox.setTag( planet ); 
    
      // Display planet data
      checkBox.setChecked( planet.isChecked() );
      textView.setText( planet.getName() );      
    
      return convertView;
    }
    
      }
    
      public Object onRetainNonConfigurationInstance() {
        return planets ;
      }
    
      public void comments (View view) {
      Intent myintent = new Intent (getApplicationContext(), DB.class);
      myintent.putExtra("name", FavList);
      startActivity(myintent);
      }
    }
    

    DB.class 看起来像:

    public class DB extends ListActivity {
    
    private final String SAMPLE_DB_NAME = "myFriendsDb";
    private final String SAMPLE_TABLE_NAME = "friend";
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        ArrayList<String> NumList = getIntent().getStringArrayListExtra("name");
        ArrayList<String> results = new ArrayList<String>();
        SQLiteDatabase sampleDB = null;
    
        try {
            sampleDB =  this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
    
            sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                    SAMPLE_TABLE_NAME +
                    " (FirstName VARCHAR);");
    
            for(String str: NumList){
                sampleDB.execSQL("INSERT INTO " +
                            SAMPLE_TABLE_NAME +
                            " ( FirstName ) Values ('"+str+"');");
                }
    
    
            Cursor c = sampleDB.rawQuery("SELECT FirstName FROM " +
                    SAMPLE_TABLE_NAME +
                    " where FirstName > 10 LIMIT 5", null);
    
            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        String firstName = c.getString(c.getColumnIndex("FirstName"));
                        results.add("" + firstName);
                    }while (c.moveToNext());
                } 
            }
    
            this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
    
        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (sampleDB != null) 
                sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
                sampleDB.close();
        }
    }
    }
    

    【讨论】:

    • 您好,感谢您的回答。我会尝试理解您的代码并在我的应用程序上进行测试。 =)
    • 嗨,别担心,如果你不能让它工作,请告诉我:)
    • 您好,在您列出行星的字符串数组的代码中,您是否对字符串数组进行了硬编码?因为,在我的应用程序中,我列出名称的字符串数组String[] buddiesList用于 Toast 消息,但我将其注释掉。 String 数组中的姓名并非来自 Android 内置联系人列表。而且我不确定是否需要对我的字符串数组进行编码。
    • 嗯,是的。安卓手机的联系人在列表中。每当用户在手机中添加联系人姓名时,它都会进入我的 ListView。
    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    相关资源
    最近更新 更多