2012-09-13 56 views
0

我有CheckBox問題。那麼兩個問題。
CheckBox問題:項目選擇和SQLite數據庫 - ANDROID

  1. 當我檢查複選框中的項目時,也檢查其他項目。
  2. 我無法將名稱(在選中之後)捕獲到SQLiteDatabase表中。

我的應用程序有一個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 = ""; 

我不知道,我已經錯編碼。我需要能夠將名稱插入到數據庫表中,並且我想確保在檢查名稱時不應檢查其他名稱。任何人都可以幫助我?
謝謝! =)

回答

0

這裏是一個與行星的名字作爲一個例子,只是改變琴絃聯繫人姓名:

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

您好,感謝你的答案。我會嘗試瞭解您的代碼並在我的應用中測試它。 =) – Preeyah

+0

嗨,不用擔心,請讓我知道如果你不能得到它的工作:) – fasheikh

+0

當然,我會讓你知道,謝謝:) – Preeyah