Android:SQLite获取错误的数据

时间:2012-10-17 14:16:51

标签: android sqlite

我的问题是,当我打开ViewContact类时,所有字段都是空白的,除了名称,它显示了注释条目。我没有在SQLite或一般数据库方面的经验。我会发布所有相关代码。我认为这可能与光标有关,但同样,我对此还不太了解。谢谢你的帮助。

ContactsMenu class

package com.emailandcontactmanager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ContactsMenu extends Activity {


    ListView listView;
    public static final String fields[] = { DatabaseSetup.colName, DatabaseSetup.colMail, DatabaseSetup.colPhone1,
                                                DatabaseSetup.colPhone2,  DatabaseSetup.colAddress,  DatabaseSetup.colNotes };
    Cursor cursor;

    public static String name, email, phone1, phone2, address, notes;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.managecontacts);
        listView = (ListView) findViewById(R.id.lstContacts); 
        DatabaseSetup.init(this); 

        Button btnAddItem = (Button) findViewById(R.id.btnAddContact);
        btnAddItem.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent addItem = new Intent(v.getContext(), AddContact.class);
            startActivity(addItem);
        }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> listView, View view, 
                int position, long id) {
        // Get the cursor, positioned to the corresponding row in the result set
            //cursor = DatabaseSetup.getContactData();
        Cursor cursor = (Cursor) listView.getItemAtPosition(position);

                String selectedName = cursor.getString(cursor.getColumnIndexOrThrow("Name"));
                String selectedEmail = cursor.getString(cursor.getColumnIndexOrThrow("Email"));
                String selectedPhone1 = cursor.getString(cursor.getColumnIndexOrThrow("Phone1"));
                String selectedPhone2 = cursor.getString(cursor.getColumnIndexOrThrow("Phone2"));
                String selectedAddress = cursor.getString(cursor.getColumnIndexOrThrow("Address"));
                String selectedNotes = cursor.getString(cursor.getColumnIndexOrThrow("Notes"));

                setName(selectedName);
                setName(selectedEmail);
                setName(selectedPhone1);
                setName(selectedPhone2);
                setName(selectedAddress);
                setName(selectedNotes);


                Intent viewItem = new Intent(view.getContext(), ViewContact.class);
                startActivity(viewItem);

        }
        }); 

    }
        @Override
        protected void onPause() {
            listView.setAdapter(null);
            cursor.close();
            DatabaseSetup.deactivate();
            super.onPause();
        }

        @Override
        protected void onResume() {
            super.onResume();
            DatabaseSetup.init(this);
            //Updated
            cursor = DatabaseSetup.getContactData(); 
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, fields, new int[] {R.id.item_text,
                                                                R.id.item_text2,  R.id.item_text3,  R.id.item_text4,
                                                                R.id.item_text5,  R.id.item_text6})
            listView.setAdapter(adapter); 
        }

        public void setName(String selectedName) {
            name = selectedName;
        }

        public void setEmail(String selectedEmail) {
            email = selectedEmail;
        }

        public void setPhone1(String selectedPhone1) {
            phone1 = selectedPhone1;
        }

        public void setPhone2(String selectedPhone2) {
            phone2 = selectedPhone2;
        }

        public void setAddress(String selectedAddress) {
            address = selectedAddress;
        }

        public void setNotes(String selectedNotes) {
            notes = selectedNotes;
        }


        public static String getName() {
            String itemName = name;
            return itemName;        
        }

        public static String getEmail() {
            String itemEmail = email;
            return itemEmail;       
        }

        public static String getPhone1() {
            String itemPhone1 = phone1;
            return itemPhone1;      
        }

        public static String getPhone2() {
            String itemPhone2 = phone2;
            return itemPhone2;      
        }

        public static String getAddress() {
            String itemAddress = address;
            return itemAddress;     
        }

        public static String getNotes() {
            String itemNotes = notes;
            return itemNotes;       
        }

////////////////MENU////////////////////////////////////////////////////////////////////////////////
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
            switch (which){ 
            case DialogInterface.BUTTON_POSITIVE: 
                finish();
                break; 

            case DialogInterface.BUTTON_NEGATIVE: 
                //Nothing happens on No button click, and the menu closes
                break; 
            } 
        } 
    }; 

    @Override
    public boolean onCreateOptionsMenu(Menu mainmenu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, mainmenu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final CharSequence[] items = {"Contacts list", "Add Contact"};

        switch (item.getItemId()) {
            case R.id.help:     AlertDialog.Builder builder = new AlertDialog.Builder(this);
                                builder.setTitle("Select a function to revice information about it.");
                                builder.setItems(items, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int selected) {
                                        switch(selected){
                                        case 0:
                                            Toast.makeText(getApplicationContext(),
                                                    "Allows you to view the selected item and make editations to it or delete it.",
                                                    Toast.LENGTH_LONG).show();
                                            break;
                                        case 1:
                                            Toast.makeText(getApplicationContext(),
                                                    "Allows you to add a new contact by bringing up a screen where the nececary information can be entered.",
                                                    Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                                builder.show();
                                break;

                                case R.id.back:     AlertDialog.Builder builderBack = new AlertDialog.Builder(this); 
                                                    builderBack.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener) 
                                                    .setNegativeButton("No", dialogClickListener).show(); 
                                break;
        }
        return true;

    }
}

ViewContacts类

package com.emailandcontactmanager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ViewContact extends Activity {

    EditText nameField, mailield, phoneField1, phoneField2, addressField, notesField;

    String name, mail, phone1, phone2, address, notes;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewcontact);

        nameField = (EditText) findViewById(R.id.textName);
        mailield = (EditText) findViewById(R.id.textMail);
        phoneField1 = (EditText) findViewById(R.id.textPhone1);
        phoneField2 = (EditText) findViewById(R.id.textPhone2);
        addressField = (EditText) findViewById(R.id.textAddress);
        notesField = (EditText) findViewById(R.id.textNotes);

        name =ContactsMenu.getName();
        mail =ContactsMenu.getEmail();
        phone1 =ContactsMenu.getPhone1();
        phone2 =ContactsMenu.getPhone2();
        address =ContactsMenu.getAddress();
        notes =ContactsMenu.getNotes();

        nameField.setText(name, TextView.BufferType.EDITABLE);
        mailield.setText(mail, TextView.BufferType.EDITABLE);
        phoneField1.setText(phone1, TextView.BufferType.EDITABLE);
        phoneField2.setText(phone2, TextView.BufferType.EDITABLE);
        addressField.setText(address, TextView.BufferType.EDITABLE);
        notesField.setText(notes, TextView.BufferType.EDITABLE);

        Button btnEditContact = (Button) findViewById(R.id.btnEditContact);
        btnEditContact.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            editContact();
        }
        });

        Button btnDeleteContact = (Button) findViewById(R.id.btnEditContact);
        btnDeleteContact.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            deleteContact();
        }
        });

        Button btnEditTags = (Button) findViewById(R.id.btnEditContact);
        btnEditTags.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent editTags = new Intent(v.getContext(), EditContactTags.class);
            startActivity(editTags);
        }
        });
    }

    public void editContact(){

    }

    public void deleteContact(){

    }

}

DatabaseSetup类

package com.emailandcontactmanager;

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 

/* 
 * usage:  
 * DatabaseSetup.init(egActivityOrContext); 
 * DatabaseSetup.createEntry() or DatabaseSetup.getContactNames() or DatabaseSetup.getDb() 
 * DatabaseSetup.deactivate() then job done 
 */ 

class DatabaseSetup extends SQLiteOpenHelper { 
static DatabaseSetup instance = null; 
static SQLiteDatabase db = null; 

public static void init(Context context) { 
    if (null == instance) { 
        instance = new DatabaseSetup(context); 
        } 
    } 

public static SQLiteDatabase getDb() { 
    if (null == db) { 
        db = instance.getWritableDatabase(); 
        } 
    return db; 
    } 

public static void deactivate() { 
    if (null != db && db.isOpen()) { 
        db.close(); 
        } 
    db = null; 
    instance = null; 
    } 

public static long createEntry(String name, String mail, String phone1, 
        String phone2, String address, String notes) { 
    ContentValues cv = new ContentValues(); 
    cv.put(colName, name); 
    cv.put(colMail, mail); 
    cv.put(colPhone1, phone1); 
    cv.put(colPhone2, phone2); 
    cv.put(colAddress, address); 
    cv.put(colNotes, notes); 
    return getDb().insert(contactsTable, null, cv); 

    } 
/*  Old 
public static Cursor getContactNames() { 
    // TODO Auto-generated method stub 
    String[] columns = new String[] {"_id", colName }; 
    return getDb().query(contactsTable, columns, null, null, null, null, 
            null); 
    } 
*/
public static Cursor getContactData(){
    String[] columns = new String[] {"_id", colName, colMail, colPhone1, colPhone2, colAddress, colNotes }; 
    return getDb().query(contactsTable, columns, null, null, null, null, 
            null); 
    }

DatabaseSetup(Context context) { 
    super(context, dbName, null, dbVersion); 
    } 

@Override 
public void onCreate(SQLiteDatabase db) { 
    // TODO Auto-generated method stub 
    db.execSQL("CREATE TABLE IF NOT EXISTS " + contactsTable 
            + " (_id integer primary key autoincrement, " + colName 
            + " TEXT NOT NULL, " + colMail + " TEXT NOT NULL, " + colPhone1 
            + " TEXT NOT NULL, " + colPhone2 + " TEXT NOT NULL, " 
            + colAddress + " TEXT NOT NULL, " + colNotes 
            + " TEXT NOT NULL)"); 

    db.execSQL("CREATE TABLE IF NOT EXISTS " + templatesTable 
            + " (_id integer primary key autoincrement, " + colSubject 
            + " TEXT NOT NULL, " + colBody + " TEXT NOT NULL)"); 

    db.execSQL("CREATE TABLE IF NOT EXISTS " + tagsTable 
            + " (_id integer primary key autoincrement, " + colTagName 
            + " TEXT NOT NULL, " + colContact + " TEXT NOT NULL)"); 

    } 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("DROP TABLE IF EXISTS " + contactsTable); 
    db.execSQL("DROP TABLE IF EXISTS " + templatesTable); 
    db.execSQL("DROP TABLE IF EXISTS " + tagsTable); 
    onCreate(db); 
    } 

static final String dbName = "DB"; 
static final int dbVersion = 1; 
static final String contactsTable = "Contacts"; 
static final String colName = "Name"; 
static final String colMail = "Email"; 
static final String colPhone1 = "Phone1"; 
static final String colPhone2 = "Phone2"; 
static final String colAddress = "Address"; 
static final String colNotes = "Notes"; 

static final String templatesTable = "Templates"; 
static final String colSubject = "Subject"; 
static final String colBody = "Body"; 

static final String tagsTable = "Tags"; 
static final String colTagName = "Name"; 
static final String colContact = "Contact"; 

} 

Logcat条目

10-22 14:49:51.418: E/AndroidRuntime(959): FATAL EXCEPTION: main
10-22 14:49:51.418: E/AndroidRuntime(959): java.lang.RuntimeException: Unable to resume activity {com.emailandcontactmanager/com.emailandcontactmanager.ContactsMenu}: java.lang.IllegalStateException: trying to requery an already closed cursor  android.database.sqlite.SQLiteCursor@4138a990
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2443)
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2471)
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1172)
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.os.Looper.loop(Looper.java:137)
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.app.ActivityThread.main(ActivityThread.java:4340)
10-22 14:49:51.418: E/AndroidRuntime(959):  at java.lang.reflect.Method.invokeNative(Native Method)
10-22 14:49:51.418: E/AndroidRuntime(959):  at java.lang.reflect.Method.invoke(Method.java:511)
10-22 14:49:51.418: E/AndroidRuntime(959):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-22 14:49:51.418: E/AndroidRuntime(959):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-22 14:49:51.418: E/AndroidRuntime(959):  at dalvik.system.NativeStart.main(Native Method)
10-22 14:49:51.418: E/AndroidRuntime(959): Caused by: java.lang.IllegalStateException: trying to requery an already closed cursor  android.database.sqlite.SQLiteCursor@4138a990
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.app.Activity.performRestart(Activity.java:4508)
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.app.Activity.performResume(Activity.java:4531)
10-22 14:49:51.418: E/AndroidRuntime(959):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2433)
10-22 14:49:51.418: E/AndroidRuntime(959):  ... 10 more

1 个答案:

答案 0 :(得分:1)

您的问题是您没有正确使用SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)。您有from数组,其中包含要从表中显示的列,to数组应包含显示列的视图。

to中的字段数应该等于from,否则您将拥有的行为只有from中的第一列映射到R.id.item_text }。

<强>更新

由于您只想显示要显示的名称列,因此请勿使用ListView填充游标cursor = (Cursor) listView.getItemAtPosition(position);。你应该替换:

Cursor cursor = (Cursor) listView.getItemAtPosition(position);

使用:

Cursor cursor = DatabaseSetup.getContactData();
StartManagingCursor(cursor);
cursor.moveToFirst();

由于您稍后使用此cursor来填充传递给其他活动的值,因此您无法从listView.getItemAtPosition(position);获取该值,因为位置position只有一个项目(是名称列),因此其他项目提供NullPointerException,因为从cursor

返回的listView.getItemAtPosition(position);中不存在这些项目

更新2:

此外:

setName(selectedName);
setName(selectedEmail);
setName(selectedPhone1);
setName(selectedPhone2);
setName(selectedAddress);
setName(selectedNotes);

应该是:

setName(selectedName);
setEmail(selectedEmail);
setPhone1(selectedPhone1);
setPhone2(selectedPhone2);
setAddress(selectedAddress);
setNotes(selectedNotes);