如何使用编辑文本,微调器和按钮将数据插入sqlite数据库?通过android编码

时间:2012-07-11 01:22:34

标签: android android-edittext android-spinner android-button sqlite

我有1个Spinner,4个Edittext和一个Button。保存按钮将信息保存到SQLite数据库中。哦,我得到“强制关闭”的消息。

我需要帮助谢谢。以下是2个类的代码。

PersonalInfo类

public class PersonalInfo extends Activity
{
    Button btnSave, btnBack;
    EditText txtLikes, txtDislikes, txtDate, txtType;
    Spinner nameSpinner;



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

        /*try{
        String destPath = "/data/data" + getPackageName() +
                "/databases/AnniversaryDB";
        File f = new File(destPath);
        if(!f.exists())
        {
            CopyDB(getBaseContext().getAssets().open("AnniversaryDB"),
                    new FileOutputStream(destPath));
        }
    }catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }catch (IOException e)
    {
        e.printStackTrace();
    }*/

        InfoDBAdapter dbA = new InfoDBAdapter(this);

        // ---add a contact---
        dbA.open();

        long id = dbA.insertContact("Kanak Priya", "24/6/1990", "Birthday", "Painting", "Bungee jumping");
        id = dbA.insertContact("Joanne Liew", "15/8/1990", "Birthday", "Skating", "Yoga");

        dbA.close();

        // ---get all contacts---

        dbA.open();
        Cursor c = dbA.getAllContacts();
        if (c.moveToFirst())
        {
            do
            {
                DisplayContact(c);
            } while (c.moveToNext());
        }
        dbA.close();

        btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {

                    Spinner nameSpinner = (Spinner) findViewById(R.id.nameSpinner);
                    String NameValue = nameSpinner.getSelectedItem().toString();

                    EditText txtDate = (EditText) findViewById(R.id.txtDate);
                    String DateValue = txtDate.getText().toString();

                    EditText txtType = (EditText) findViewById(R.id.txtType);
                    String TypeValue = txtType.getText().toString();

                    EditText txtLikes = (EditText) findViewById(R.id.txtLikes);
                    String LikesValue = txtLikes.getText().toString();

                    EditText txtDislikes = (EditText) findViewById(R.id.txtDislikes);
                    String DislikesValue = txtDislikes.getText().toString();


                    Toast.makeText(getBaseContext(),
                            "Your info is saved successfully!",
                            Toast.LENGTH_SHORT).show();

                }
            });

        btnBack = (Button) findViewById(R.id.btnMain);
        btnBack.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    finish();

                }
            });



        /*
         * //---get a contact--- db.open(); Cursor c = db.getContact(2); if
         * (c.moveToFirst()) DisplayContact(c); else Toast.makeText(this,
         * "No contact found", Toast.LENGTH_LONG).show(); db.close();
         */

        /*
         * //---update contact--- db.open(); if (db.updateContact(1,
         * "Kanak Priya", "24/6/1990", "Birthday", "Painting", "Bungee jumping")) Toast.makeText(this,
         * "Update successful.", Toast.LENGTH_LONG).show(); else
         * Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
         * db.close();
         */

        /*
         * //---delete a contact--- db.open(); if (db.deleteContact(1))
         * Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
         * else Toast.makeText(this, "Delete failed.",
         * Toast.LENGTH_LONG).show(); db.close();
         */

    }// end onCreate()

    /*public void CopyDB(InputStream inputStream,
        OutputStream outputStream)
        throws IOException 
    {
            //---copy 1K bytes at a time---
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) 
            {
                outputStream.write(buffer, 0, length);
            }
            inputStream.close();
            outputStream.close();
    }*/

    public void DisplayContact(Cursor c)
    {
        Toast.makeText(
                this,
                "id: " + c.getString(0) + "\n" + "Name: " + c.getString(1)
                        + "\n" + "Date:  " + c.getString(2) + "\n" + "Type: " + c.getString(3) + "\n" + "Likes: " + c.getString(4)
                       + "\n" + "Dislikes: " + c.getString(5),  Toast.LENGTH_LONG)
                .show();
    }

}

InfoDBAdapter类

public class InfoDBAdapter
{
    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "name";
    public static final String KEY_DATE = "date";
    public static final String KEY_TYPE = "type";
    public static final String KEY_LIKES = "likes";
    public static final String KEY_DISLIKES = "dislikes";

    private static final String TAG = "InfoDBAdapter";

    private static final String DATABASE_NAME = "AnniversaryDB";
    private static final String DATABASE_TABLE = "personalInfo";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE = "create table personalInfo (_id integer primary key autoincrement, "
            + "name text not null, date numeric not null, type text not null" +
            "likes text not null, dislikes text not null);";

    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public InfoDBAdapter(Context ctx)
    {
        this.context = ctx;
        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();
            }
        }// end onCreate()

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS personalInfo");
            onCreate(db);
        }// end onUpgrade()

    }// end DatabaseHelper

    // ---opens the database---
        public InfoDBAdapter open() throws SQLException
        {
            db = DBHelper.getWritableDatabase();
            return this;
        }// end open()

        // ---closes the database---
        public void close()
        {
            DBHelper.close();
        }// end close()

        // ---insert a contact into the database---
        public long insertContact(String name, String date, String type, String likes, String dislikes)
        {
            ContentValues values = new ContentValues();
            values.put(KEY_NAME, name);
            values.put(KEY_DATE, date);
            values.put(KEY_TYPE, type);
            values.put(KEY_LIKES, likes);
            values.put(KEY_DISLIKES, dislikes);
            return db.insert(DATABASE_TABLE, null, values);
        }// end insertContact()

        // ---deletes a particular contact---
        public boolean deleteContact(long rowId)
        {
            return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
        }// end deleteContact()

        // ---retrieves all the contacts---
        public Cursor getAllContacts()
        {
            return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME,
                    KEY_DATE, KEY_TYPE, KEY_LIKES, KEY_DISLIKES }, null, null, null, null, null);
        }// end getAllContacts()

        // ---retrieves a particular contact---
        public Cursor getContact(long rowId) throws SQLException
        {
            Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                    KEY_ROWID, KEY_NAME, KEY_DATE, KEY_TYPE, KEY_LIKES, KEY_DISLIKES }, KEY_ROWID + "=" + rowId,
                    null, null, null, null, null);
            if (mCursor != null)
            {
                mCursor.moveToFirst();
            }
            return mCursor;
        }// end getContact()

        // ---updates a contact---
        public boolean updateContact(long rowId, String name, String date, String type, String likes, String dislikes)
        {
            ContentValues args = new ContentValues();
            args.put(KEY_NAME, name);
            args.put(KEY_DATE, date);
            args.put(KEY_TYPE, type);
            args.put(KEY_LIKES, likes);
            args.put(KEY_DISLIKES, dislikes);
            return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
        }// end updateContact()

}//end DBAdapter        

1 个答案:

答案 0 :(得分:1)

以下是要检查的内容:

1)确保布局中的每个元素都定义了布局高度和宽度。这些不会给出编译时错误,但会使应用程序崩溃。

    android:layout_width="fill_parent"
    android:layout_height="wrap_content"

2)确保在使用之前首先检索每个元素:

Button btnSave = (Button)findViewById(R.id.someId);

3)检查检索到的ui元素是否为空。

if(btnSave == null)      System.out.println(“这将崩溃”);

4)在调试模式下运行。设置断点。观察价值观,看看什么是空的。崩溃通常意味着null或数组越界。

5)检查您看到致命的日志消息,红色。现在仔细聆听,在包名称的一行上单击它下面的一行或两行。像com.yourcompany.xyx(在你的情况下看起来可能是main.page) 它(eclipse)会带你到崩溃点。点击android类名称对你没有任何好处。只需点击包含您的包名称的红色致命下方最高点。了解包名非常重要。告诉我们这是哪一行。