CheckBox问题:项目选择& SQLite数据库 - ANDROID

时间:2012-09-13 07:48:50

标签: android listview checkbox insert sqlite

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

  1. 当我勾选复选框中的项目时,也会检查其他项目。
  2. 我无法将名称(在选中后)捕获到SQLiteDatabase表中。
  3. 我的应用程序有一个ListView的联系人姓名(从android内置联系人列表中检索)和复选框。此外,用户可以在列表中多选名称 我在一个班级里有2个班级 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 = "";
    

    我不确定我编码错误的地方。我需要能够将名称插入数据库表,我想确保当我检查名称时,不应检查其他名称。有人可以帮帮我吗? 谢谢! =)

1 个答案:

答案 0 :(得分:0)

以下以Planet名称为例,只需将字符串更改为联系人姓名:

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();
    }
}
}