好的,我几乎所有东西都在工作。唯一的问题是,每当我单击通过对话框添加到列表视图中的新条目时,应用程序就会崩溃,而不是在 toast 中显示电话号码。我想要它做的如下(大多数步骤都正常工作)
- 我通过模拟器上的菜单按钮进入对话框,然后单击对话框的菜单项。
- 我输入姓名和电话号码(我用我的作为测试)
- 它将数据作为联系人对象传递给 ArrayAdapter,ArrayAdapter 将添加到 MainActivity 中的 ListView。
- 当我单击新条目时,它会获取联系人的姓名,然后在数据库中查找与该姓名关联的电话号码并将其显示在 toast 中。(该部分无法正常工作,导致上述崩溃)
AddContactFragment.java:
package com.example.java2lab10_lefelhocz;
import com.example.java2lab10_lefelhocz.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.*;
public class AddContactFragment extends DialogFragment
{
private EditText txtNameEdit;
private EditText txtPhoneEdit;
private LayoutInflater inflater;
// called when the DialogFragment is created
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// create the dialog builder
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater object
inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.add_contact, null));
builder.setTitle("Add a Contact");
builder.setPositiveButton("Add", new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
txtNameEdit = (EditText)getDialog().findViewById(R.id.txtNameEdit);
txtPhoneEdit = (EditText)getDialog().findViewById(R.id.txtPhoneEdit);
MainActivity ma = (MainActivity)getActivity();
ma.addContact(txtNameEdit.getText().toString(), txtPhoneEdit.getText().toString());
}
});
builder.setNegativeButton("Cancel", new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
return builder.create();
}
}
联系方式.java:
// Project: Java2Lab10_Lefelhocz
// File: Contact.java
// Date: 11/1/12
// Description: This class represents a contact
package com.example.java2lab10_lefelhocz;
public class Contact
{
//private variables
private int _id;
private String _name;
private String _phone_number;
// Empty constructor
public Contact()
{
}
// constructor
public Contact(int id, String name, String _phone_number)
{
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Contact(String name, String _phone_number)
{
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID()
{
return this._id;
}
// setting id
public void setID(int id)
{
this._id = id;
}
// getting name
public String getName()
{
return this._name;
}
// setting name
public void setName(String name)
{
this._name = name;
}
// getting phone number
public String getPhoneNumber()
{
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number)
{
this._phone_number = phone_number;
}
public String toString(){
return _name;
}
}
数据库处理程序.java
// Project: Java2Lab10_Lefelhocz
// File: DatabaseHandler.java
// Date: 04/3/13
// Description: This class handles all database operations
// Databases opened for write should be closed.
package com.example.java2lab10_lefelhocz;
import java.util.ArrayList;
import java.util.List;
import com.example.java2lab10_lefelhocz.Contact;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
// This class extends SQLiteOpenHelper and handles all database operations
public class DatabaseHandler extends SQLiteOpenHelper
{
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
// constructor
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
// Called when the database is created for the first time.
// This is where the creation of tables and the initial population of the tables should happen.
@Override
public void onCreate(SQLiteDatabase db)
{
// SQLite Create syntax
//CREATE TABLE NameOfTable(Column1 Type, Column2 Type);
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
// + KEY_PH_NO + " TEXT," + " UNIQUE (" + KEY_NAME + "))";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// adds a new contact
public void addContact(Contact contact)
{
// get the database from the SQLiteHelper
SQLiteDatabase db = this.getWritableDatabase();
// This class is used to store a set of key/values that the ContentResolver can process.
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
// SQLite Syntax
// INSERT INTO TableName(ColumnValue, ColumnValue)
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// retrieve single contact by id
public Contact getContact(int id)
{
// get the database from the SQLiteHelper
SQLiteDatabase db = this.getReadableDatabase();
// query the table and return a Cursor
// SQLite Syntax
// SELECT * FROM TableName WHERE Column=Value;
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
// Create a Contact object from the Cursor
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// close the cursor
cursor.close();
// close the database
db.close();
// return contact
return contact;
}
public Contact getContact(String name)
{
// get the database from the SQLiteHelper
SQLiteDatabase db = this.getReadableDatabase();
// query the table and return a Cursor
// SQLite Syntax
// SELECT * FROM TableName WHERE Column=Value;
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
// Create a Contact object from the Cursor
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// close the cursor
cursor.close();
// close the database
db.close();
// return contact
return contact;
}
// return a List of All Contacts in table
public List<Contact> getAllContacts()
{
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
// SQLiteDatabase db = this.getWritableDatabase();
SQLiteDatabase db = this.getReadableDatabase();
// execute a raw SQLite query
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
// create a new Contact object
Contact contact = new Contact();
// get the data from the cursor and assign it to the contact
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close the cursor
cursor.close();
// return contact list
return contactList;
}
// return Count of all Contacts in table
public int getContactsCount()
{
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
// return count
return cursor.getCount();
}
// Updating single contact
public int updateContact(Contact contact)
{
SQLiteDatabase db = this.getWritableDatabase();
// This class is used to store a set of key/values that the ContentResolver can process.
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
int n = db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
return n;
}
// Deleting single contact
public void deleteContact(Contact contact)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close(); // Closing database connection
}
// delete all the Contacts
public void deleteAllContacts()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, null, null);
db.close(); // Closing database connection
}
// returns a cursor with all the Contacts
public Cursor getAllCursor()
{
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
// execute a raw SQLite query
Cursor cursor = db.rawQuery(selectQuery, null);
// return the Cursor
return cursor;
}
}
MainActivity.java:
// Project: Java2Lab10_Lefelhocz
// File: MainActivity.java
// Date: 04/3/13
// Description: This class is the main activity for the application
// Its purpose is to demonstrate the SQLiteHelper and to test
// adding, deleting, updating and listing entries in the database.
package com.example.java2lab10_lefelhocz;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AdapterView.OnItemClickListener
{
private DatabaseHandler dbh;
private ListView contactsListView ;
private ArrayAdapter<Contact> adapter ;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsListView = (ListView) findViewById( R.id.contactsListView );
dbh = new DatabaseHandler(this);
// delete all entries in Contacts table
dbh.deleteAllContacts();
// set the Activity to listen for the onItemClick event
contactsListView.setOnItemClickListener(this);
// create the ArrayAdapter
adapter = createAdapter();
// Set the ArrayAdapter as the ListView's adapter.
contactsListView.setAdapter( adapter );
// create the database handler object
}
protected ArrayAdapter<Contact> createAdapter() {
// TODO Auto-generated method stub
List<Contact> contacts = dbh.getAllContacts();
ArrayAdapter<Contact> contactsAdapter = new ArrayAdapter<Contact> (this,android.R.layout.simple_list_item_1, contacts);
return contactsAdapter;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// this method displays the current list of Contacts
public void displayContacts()
{
// create a list of Contacts
List<Contact> contacts = dbh.getAllContacts();
// create the string builder message
StringBuilder message = new StringBuilder();
// display headings
message.append("Total: " + dbh.getContactsCount() + "\n");
message.append(String.format("%-5s%-10s%-10s\n", "Id:", "Name:", "Phone:"));
// Use list of contacts to build a StringBuffer that will be displayed in the TextView
for(Contact cn : contacts)
{
message.append(String.format("%-5s%-10s%-10s\n", cn.getID(), cn.getName(), cn.getPhoneNumber()));
}
// display the StringBuilder with all the contacts
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_add_contact:
DialogFragment myFragment = new AddContactFragment();
myFragment.show(getFragmentManager(), "customDialog");
default:
return super.onOptionsItemSelected(item);
}
}
public void addContact(String newName, String newPhone)
{
Contact c = new Contact(newName, newPhone);
dbh.addContact(c);
adapter.add(c);
}
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
Context context = null;
// TODO Auto-generated method stub
Contact c1 = dbh.getContact(((TextView)view).getText().toString());
Toast.makeText(context, "Phone Number: " + c1.getPhoneNumber(), Toast.LENGTH_LONG).show();
}
}