btnAdd应该打开SecondActivity,它会收集一个新的电子邮件地址并将其返回到第一个Activity并存储在数组中。然后它将添加新的电子邮件地址以显示在ListView中 此外,每次我打开应用程序时,它会一直附加到列表中,如果我从4个电子邮件地址开始,每次运行应用程序时,它都会添加到它中,从而给出了这个错误。
MainActivity.java
public class MainActivity extends ActionBarActivity {
DBAdapter db;
ListView listContacts;
Button btnAdd;
int selectedItem = 0;
String name, email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listContacts = (ListView)findViewById(R.id.listContacts);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Start 2nd Activity
startActivity(new Intent("ca.nbcc.lizgoldston.SecondActivity"));
finish();
if(selectedItem != 0){
insertContact(name, email);
}
}
});
db = new DBAdapter(this); // Set up our DBHelper
addContacts(); // Add some generic data to DB for display purposes
listContacts(); // Display the records in a ListView
// Set the Listener on the ListView and change background color for selected item
listContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listContacts.setBackgroundColor(Color.WHITE);
listContacts.getChildAt(position).setBackgroundColor(Color.GRAY);
parent.getItemAtPosition(position); // Get the ListItem at position clicked
listContacts.setSelection(position);
listContacts.setSelected(true);
String info = parent.getItemAtPosition(position).toString(); // Get the String with contact info
int contactId = Integer.parseInt(info.substring(0,info.indexOf(":"))); // Parse for contact id
selectedItem = contactId; // Set the selectedItem id
Toast.makeText(getApplicationContext(), info + " clicked", Toast.LENGTH_SHORT).show();
}
});
}
public void addContacts() {
// Add some generic contact records for display purposes
db.open();
if (db.insertContact("Sally Brown", "sally@nbcc.ca") >= 0){
Toast.makeText(this, "Add successful.", Toast.LENGTH_SHORT).show();
}
if (db.insertContact("John Smith", "john@nbcc.ca") >= 0) {
Toast.makeText(this, "Add successful.", Toast.LENGTH_SHORT).show();
}
if (db.insertContact("Tom Brown", "tom@nbcc.ca") >= 0){
Toast.makeText(this, "Add successful.", Toast.LENGTH_SHORT).show();
}
if (db.insertContact("Susie Brawn", "susie@nbcc.ca") >= 0){
Toast.makeText(this, "Add successful.", Toast.LENGTH_SHORT).show();
}
db.close();
}
public void getContacts() {
// Get all contacts
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst()) // As long as there are records
{
do {
displayContact(c);
} while (c.moveToNext());
}
db.close();
}
public Contact getContact(int _id) {
// Get a contact based on id provided
Contact contact = new Contact();
db.open();
Cursor c = db.getContact(_id);
if (c.moveToFirst()){ // As long as there are records
displayContact(c); // Display the specific contact
contact.setId(c.getInt(0));
contact.setName(c.getString(1));
contact.setEmail(c.getString(2));
}
else {
Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show();
}
db.close();
return contact;
}
// Method to update a contact with the info provided
public void updateContact(int _id, String _name, String _email) {
// Update contact
// This could obviously be made 'prettier' by adding confirmation dialog, etc.
db.open();
if (db.updateContact(_id, _name, _email)) {
}else {
Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
}
db.close();
}
// Method to delete contact with the id provided
public void insertContact(String name, String email) {
// Add Contact
db.open();
if (db.insertContact(name, email) == 1) {
Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this, "Add failed.", Toast.LENGTH_LONG).show();
}
db.close();
}
public void displayContact(Cursor c)
{
// Display specific Contact in the cursor provided
Toast.makeText(this,
"id: " + c.getInt(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Email: " + c.getString(2),
Toast.LENGTH_LONG).show();
}
public void listContacts(){
// Show the database contacts in a ListView
List<String> contactList = getContactList();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, contactList);
listContacts.setAdapter(adapter);
}
public List<String> getContactList(){
List<String> contactList = new ArrayList<String>();
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{
do {
contactList.add(c.getString(0) + ":" + c.getString(1) + ":" + c.getString(2));
} while (c.moveToNext());
}
db.close();
return contactList;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Android清单
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="@string/app_name" >
</activity>
</application>
SecondActivity.java
public class SecondActivity extends ActionBarActivity {
TextView txtEmail;
EditText txtAddress;
Button btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondactivity);
txtEmail = (TextView)findViewById(R.id.txtEmail);
txtAddress = (EditText)findViewById(R.id.txtAddress);
btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == findViewById(R.id.btnSave)) {
MainActivity main = new MainActivity();
main.email = txtAddress.getText().toString();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_email, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
DBAdapter.java
public class DBAdapter {
static final String KEY_ROWID = "id";
static final String KEY_NAME = "name";
static final String KEY_EMAIL = "email";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB";
static final String DATABASE_TABLE = "contacts";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE =
"CREATE TABLE contacts (id integer primary key autoincrement, "
+ "name text not null, email text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context _context){
this.context = _context;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ". This will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Downgrading database from version " + oldVersion + " to "
+ newVersion + ". This will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
// Open the db
public DBAdapter open() throws SQLException{
db = DBHelper.getWritableDatabase();
return this;
}
// Closes the db
public void close(){
DBHelper.close();
}
// Insert a new contact
public long insertContact(String name, String email){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Deletes a specific contact
public boolean deleteContact(long rowId){
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// Getting All Contacts in a List
public List<Contact> getAllContactsList() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contacts";
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setEmail(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Retrieve all contacts
public Cursor getAllContacts(){
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_EMAIL}, null, null, null, null, null);
}
// Retrieve a specific contact
public Cursor getContact(long rowId) throws SQLException{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// Update a contact
public boolean updateContact(long rowId, String name,
String email){
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
Contact.java
public class Contact {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
activity_main.xml中
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:text="Email Addresses..."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<ListView
android:id="@+id/listContacts"
android:layout_width="fill_parent"
android:layout_height="450dp"
android:layout_below="@+id/textView" />
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:layout_below="@+id/listContacts"
android:layout_gravity="bottom" />
</LinearLayout>
activity_secondactivity.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="ca.nbcc.lizgoldston.emaillistapp.email"
android:orientation="vertical"
android:clickable="true">
<TextView
android:id="@+id/txtEmail"
android:text="Add a new email... "
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/txtAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="enter a new email here"
android:inputType="textEmailAddress"
android:layout_marginTop="25dp"/>
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtAddress"
android:layout_marginTop="15dp"
android:text="SAVE"/>
</LinearLayout>
答案 0 :(得分:0)
试试这个,
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Start 2nd Activity
if(selectedItem != 0){
insertContact(name, email);
}
startActivity(new Intent(MainActivity.this, SecondActivity.class));
finish()
}
});