0

我是 android 新手,在我的应用程序中我需要创建数据库,当用户将一些东西写入 EditText 时,我需要将它保存到数据库中,但我实际上不知道我将如何去做。所以请有人帮帮我。我已经创建了保存数据的提交按钮,现在我只需要创建一个数据库。

在这里,我给出了一个名为“Invitation.java”的活动类,其中包含

         package com.ggit.trip.caster;

     import android.content.Intent;
     import android.os.Bundle;
     import android.util.Log;
     import android.view.View;
     import android.view.View.OnClickListener;
     import android.widget.Button;
     import android.widget.EditText;

    public class Invitation extends AppBaseActivity {

protected static final String Tag = "Invitation Activity";

private Button submit2;
private Button exit2;

private EditText Edit1;
private EditText Edit2;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invitation);

    registerBaseActivityReceiver();

    submit2 = (Button) findViewById(R.id.sub2_button1);
    exit2=(Button)findViewById(R.id.button2);

    Edit1 = (EditText) findViewById(R.id.editText1);
    Edit2 = (EditText) findViewById(R.id.editText2);

    submit2.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            Log.d(Tag, "EditText : " + Edit1.getText().toString());
            Log.d(Tag, "EditText : " + Edit2.getText().toString());

            Intent intent = new Intent(getApplicationContext(),
                    Registration.class);
            startActivity(intent);
        }
    });

    exit2.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            closeAllActivities();
                   }
    });
}

public void onDestroy() {

    super.onDestroy();
    unRegisterBaseActivityReceiver();
}

    }

现在这里名为“invitation.xml”的 Invitation.jave 类的 xml 布局包含

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/sea_01"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="28dp"
    android:text="E-mail"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="160dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:background="@drawable/rounded_edittext"
    android:ems="10"
    android:hint="     email address"
    android:inputType="textEmailAddress" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/editText1"
    android:text="Phone"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="160dp"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editText1"
    android:layout_below="@+id/textView2"
    android:background="@drawable/rounded_edittext"
    android:ems="10"
    android:hint="    phone number"
    android:inputType="phone" />

<Button
    android:id="@+id/sub2_button1"
    android:layout_width="100dp"
    android:layout_height="45dp"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/textView1"
    android:layout_marginRight="27dp"
    android:background="@drawable/gloss_nine_patch"
    android:text="Send Invitation" />

<Button
    android:id="@+id/button2"
    android:layout_width="100dp"
    android:layout_height="45dp"
    android:layout_alignLeft="@+id/textView2"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="32dp"
    android:background="@drawable/gloss_nine_patch"
    android:text="Exit" />

 </RelativeLayout>

现在我需要将这两个 EditText 的数据保存到数据库中。请写一个适当的或完整的活动类,因为我是新人。谢谢你。


@Naser 的 DataHelper.java

package i.am.arnob;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DataHelper  extends SQLiteOpenHelper{

//database version, current ver is 1.
public static final int DATABASE_VER=1;

//database Name or db name
public static final String DATABASE_NAME="dataPerson";

//table Name, table person
public static final String TABLE_PERSON="person";

//table fields name,fist name,email and domain
//public static final String KEY_NAME="name";
//public static final String KEY_FIRST_NAME="first_name";
public static final String KEY_EMAIL="email";
public static final String KEY_DOMAIN="domain";

public DataHelper(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);
    // TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    //creating string sqlTable for creating a table 
    String sqlTable = "create table " +TABLE_PERSON+ "("/* +KEY_NAME+ " text," +KEY_FIRST_NAME+ " text," */ +KEY_EMAIL+ " text," +KEY_DOMAIN+ " text);"; 
    //db.execSQL() will execute string which we provide and will create a  table with given table name and fields.
    db.execSQL(sqlTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

}
4

2 回答 2

1

在这里,我为所有功能创建了简单的类

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DBAdapter {

public static final String KEY_AOUTO = "_id";
public static final String KEY_ID_SONG = "id_song";
public static final String KEY_RATING_VALUE = "rating_value";

private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "meadia_rating";
private static final String DATABASE_TABLE_TIME = "music_rating";

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_CREATE_TIME = "create table music_rating (_id integer primary key autoincrement,"
        + "id_song text not null,rating_value text not null);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

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

    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE_TIME);

    }

    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 Savedfiles");

        onCreate(db);
    }
}

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

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

// ---insert a data into the database---
public long insert(String id_song, String rating_value) {
    ContentValues initialValues = new ContentValues();

    initialValues.put(KEY_ID_SONG, id_song);
    initialValues.put(KEY_RATING_VALUE, rating_value);

    return db.insert(DATABASE_TABLE_TIME, null, initialValues);
}

// ---deletes a particular row---
public boolean delete(long rowId) {
    return db.delete(DATABASE_TABLE_TIME, KEY_AOUTO + "=" + rowId, null) > 0;
}

// ---deletes all table data---
public void deleteAll(String table_name) {
    SQLiteDatabase db = DBHelper.getWritableDatabase();
    db.delete(table_name, null, null);
}

// ---- Search database a particular text----
public Cursor getRating(String mSongId) throws SQLException {


    Cursor mCursor = db.query(true, DATABASE_TABLE_TIME, new String[] {
            KEY_AOUTO, KEY_ID_SONG, KEY_RATING_VALUE }, KEY_ID_SONG + "="
            + mSongId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

// ---updates a title---
public boolean updateRate(String rowId, String mSongId, String rating_value) {
    ContentValues args = new ContentValues();
    args.put(KEY_ID_SONG, mSongId);
    args.put(KEY_RATING_VALUE, rating_value);

    return db.update(DATABASE_TABLE_TIME, args, KEY_AOUTO + "=" + rowId,
            null) > 0;
}

}
于 2013-09-14T08:54:22.500 回答
0

这是我的代码:

这是助手类:

public class DataHelper  extends SQLiteOpenHelper{

    //database version, current ver is 1.
    public static final int DATABASE_VER=1;

    //database Name or db name
    public static final String DATABASE_NAME="dataPerson";

    //table Name, table person
    public static final String TABLE_PERSON="person";

    //table fields name,fist name,email and domain
    public static final String KEY_NAME="name";
    public static final String KEY_FIRST_NAME="first_name";
    public static final String KEY_EMAIL="email";
    public static final String KEY_DOMAIN="domain";



    public DataHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        //creating string sqlTable for creating a table 
        String sqlTable = "create table " +TABLE_PERSON+ "(" +KEY_NAME+ " text," +KEY_FIRST_NAME+ " text," +KEY_EMAIL+ 
                " text," +KEY_DOMAIN+ " text);"; 
        //db.execSQL() will execute string which we provide and will create a table with given table name and fields.
        db.execSQL(sqlTable);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

这是您的保存按钮:

mbtnSave.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                // getting database for reading/writing purpose
                db = helper.getWritableDatabase();

                // getting data from edit text to string variables
                String name = medtName.getText().toString().trim();
                String firstName = medtFirstName.getText().toString().trim();
                String email = medtEmail.getText().toString().trim();
                String domain = medtDomain.getText().toString().trim();

                // checking for empty fields
                if (!name.equals("") && !firstName.equals("")
                        && !email.equals("") && !domain.equals("")) {

                    // contentValues will add data into key value pair which
                    // will later store in db
                    ContentValues values = new ContentValues();

                    values.put(DataHelper.KEY_NAME, name);
                    values.put(DataHelper.KEY_FIRST_NAME, firstName);
                    values.put(DataHelper.KEY_EMAIL, email);
                    values.put(DataHelper.KEY_DOMAIN, domain);

                    // insert query will insert data in database with
                    // contentValues pair.
                    db.insert(DataHelper.TABLE_PERSON, null, values);

                    toast("Added!");

                    // db.close();
                    // helper.close();
                    // created user defined method to clean the text fields
                    clean();

                    // }else{toast("proper name");}
                } else {

                    toast("Fields either empty or not proper");
                }

                // closing the database connection
                db.close();
            }
        });
于 2012-09-01T07:29:03.273 回答