-3

私の問題は、ViewContact クラスを開くと、メモのエントリを表示する名前以外のすべてのフィールドが空白になることです。私はSQLiteやデータベース全般の経験がありません。関連するすべてのコードを投稿します。カーソルに関するものかもしれませんが、これについてはまだよくわかりません。助けてくれてありがとう。

ContactsMenu クラス

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;

    }
}

ViewContact クラス

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
4

1 に答える 1

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);アイテムが 1 つしかないため取得できず、他のアイテムはから戻ったpositionNullPointerExceptioncursorlistView.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);
于 2012-10-17T14:34:01.500 に答える