我从联系簿中选择联系人,在ListView上显示联系人并将其存储在SQLite数据库中。假设我选择了3个联系人,即联系人A,联系人B,联系人C.现在,当我重新启动模拟器时,它显示我联系A,联系人B,联系人B,联系人B,联系人B,联系人C ......请参阅ListView请帮忙。我做错了什么。
MySQLHelp.java
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "userdetails";
public static final String TABLE_NAME_MSG = "usermessage";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NUMBER = "NUMBER";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_ID_MSG = "_id";
public static final String COLUMN_MSG = "message";
private static final String DATABASE_NAME = "userInformation.db";
private static final int DATABASE_VERSION = 1;
private static final String LOG = "DatabaseHelper";
// Database creation sql statement
private static final String DATABASE_CREATE_TABLE_CONTACTS = "create table "
+ TABLE_NAME + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_NAME
+ " text not null,"+COLUMN_NUMBER+" text not null,"+COLUMN_TYPE+" text not null);";
private static final String DATABASE_CREATE_TABLE_MSG = "create table "
+ TABLE_NAME_MSG + "(" + COLUMN_ID_MSG
+ " integer primary key autoincrement, " + COLUMN_MSG + " text not null);";
private static final String DATABASE_INSERT_MSG = "insert into "
+ TABLE_NAME_MSG + "(" + COLUMN_MSG+") VALUES('enter your message');";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_TABLE_CONTACTS);
database.execSQL(DATABASE_CREATE_TABLE_MSG);
database.execSQL(DATABASE_INSERT_MSG);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long insertContact(ContactItems contItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contItem.getName());
values.put(COLUMN_NUMBER, contItem.getNumber());
values.put(COLUMN_TYPE, contItem.getType());
// insert row
long result = db.insert(TABLE_NAME, null, values);
// assigning tags to todo
/*for (long tag_id : tag_ids) {
createTodoTag(todo_id, tag_id);
}*/
return result;
}
public ArrayList<ContactItems> getAllContacts() {
ArrayList<ContactItems> contactList = new ArrayList<ContactItems>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
ContactItems conItems = new ContactItems();
conItems.setName(c.getString((c.getColumnIndex(COLUMN_NAME))));
conItems.setNumber((c.getString(c.getColumnIndex(COLUMN_NUMBER))));
conItems.setType(Integer.parseInt(c.getString(c.getColumnIndex(COLUMN_TYPE))));
// adding to todo list
contactList.add(conItems);
} while (c.moveToNext());
}
return contactList;
}
public void updateMsg(String msg) {
// TODO Auto-generated method stub
// String selectQuery = "update " + TABLE_NAME_MSG+" set "+COLUMN_MSG+" = '"+msg+"' where "+COLUMN_ID_MSG+" = 1";
ContentValues values = new ContentValues();
values.put(COLUMN_MSG, msg);
SQLiteDatabase db = this.getReadableDatabase();
db.update(TABLE_NAME_MSG, values, null, null);
}
public String getMsg() {
String message ="";
String selectQuery = "SELECT * FROM " + TABLE_NAME_MSG;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
message = c.getString(c.getColumnIndex(COLUMN_MSG));
} while (c.moveToNext());
}
// TODO Auto-generated method stub
Log.e(LOG, "message = "+message);
return message;
}
public int removeData(String number) {
// TODO Auto-generated method stub
SQLiteDatabase db = this.getReadableDatabase();
//db.drawQuery(deleteQuery, null);
return db.delete(TABLE_NAME, COLUMN_NUMBER + "='" + number+"'", null) ;
}
}
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (EditText) findViewById(R.id.et_message);
//message.setFocusable(false);
spinner = (Spinner) findViewById(R.id.Spin_alert_message);
dbHelper= new MySQLiteHelper(MainActivity.this);
selectedContactList = dbHelper.getAllContacts();
ArrayAdapter<String> adp = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
alert);
spinner.setAdapter(adp);
final SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
String selectedItem = alert[position];
message.setText(selectedItem);
// loads the text that has been stored to SP and set it to
// EditText
//message.setText(pref.getString("AutoSave", ""));
// to bring cursor to front
message.setSelection(message.getText().length());
message.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
}
@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
// saving text after it is changed by the user
pref.edit().putString("AutoSave", s.toString())
.commit();
dbHelper.updateMsg( s.toString());
}
});
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
final ContactItems item = new ContactItems(
c.getString(0), c.getString(1), c.getInt(2));
item.setName(c.getString(0));
item.setNumber(c.getString(1));
item.setType(c.getInt(2));
selectedContactList.add(item);
Set<ContactItems> s = new TreeSet<ContactItems>(
new Comparator<ContactItems>() {
@Override
public int compare(ContactItems o1,
ContactItems o2) {
// for preventing duplicacy of contacts
// and calling toast
if (o1.number.equals(o2.number)) {
Toast.makeText(
getApplicationContext(),
"Selected Number Already Exists",
Toast.LENGTH_SHORT).show();
} else {
}
return o1.getNumber().compareTo(
o2.getNumber());
}
});
s.addAll(selectedContactList);
selectedContactList.clear();
selectedContactList.addAll(s);
adapter.notifyDataSetChanged();
// save the task list to preference
dbHelper.insertContact(item);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}
答案 0 :(得分:0)
假设s
是唯一ContactItems
的TreeSet,您必须输入以下代码,可能是在selectedContactList.addAll(s);
for (ContactItems item : s) {
dbHelper.insertContact(item);
}
请注意,在Comparator
上,您必须覆盖equals
方法