2013-04-04 75 views
1

好吧,我幾乎所有的工作。唯一的問題是,每當我點擊我通過我的對話框添加到列表視圖的新條目時,應用程序崩潰而不是在烤麪包中顯示電話號碼。我想要它做的如下(大多數步驟正常工作)顯示電話號碼在烤麪包

  1. 我通過模擬器上的菜單按鈕進入對話框,然後單擊我的對話框的菜單項。
  2. 我輸入一個姓名和電話號碼(我用我的測試)
  3. 它將該數據作爲聯繫人對象傳遞給ArrayAdapter,該數據添加到MainActivity的ListView中。
  4. 當我點擊新條目時,它會獲取聯繫人的姓名,然後查看數據庫中與該名稱關聯的電話號碼並將其顯示在吐司中(該部分工作不正常,導致上述情況崩潰)

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

Contact.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; 
     } 
     } 

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


    } 

回答

2

在這裏:

Context context = null; //<<<< 

你忘了將它傳遞給Toast.makeText方法之前,當前活動上下文初始化context。初始化爲:

Context context = MainActivity.this; 
+0

謝謝,會做。順便說一下,我敢打賭,我是第一個用足夠的信息提出這個問題的人。我看過的所有其他人都被認爲太模糊。 – 2013-04-04 16:03:40

+0

沒問題。有時我們需要的是另一雙眼睛來指出我們一直在折磨的事情。 – 2013-04-04 16:05:47

+0

是的,我知道對不對? – 2013-04-04 16:35:53

0

它看起來像你與null作爲上下文調用makeToast。 Android的醫生說:

Context context = getApplicationContext(); 
CharSequence text = "Hello toast!"; 
int duration = Toast.LENGTH_SHORT; 

Toast toast = Toast.makeText(context, text, duration); 
toast.show(); 
0
Toast.makeText(context, "Phone Number: " + c1.getPhoneNumber(), Toast.LENGTH_LONG).show(); 

在這一行只需更換contextgetApplicationContext()就大功告成了。 問題出在上下文被初始化爲null