将SQLite实现到Android App中

时间:2015-02-22 13:04:58

标签: java android sql

我是Android新手,我正在制作一个简单的登录/注册应用。目前我的问题是SQLite数据库创建没有执行意味着它不会使我的表。我做了:

Register.java

public class Register extends Activity implements View.OnClickListener {

    EditText insertUsername, insertName, insertPassword, insertFinal;
    Button create;
    LoginDBAdapter loginHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_register);

        insertUsername = (EditText) findViewById(R.id.insertUsername);
        insertName = (EditText) findViewById(R.id.insertName);
        insertPassword = (EditText) findViewById(R.id.insertPassword);
        insertFinal = (EditText) findViewById(R.id.insertFinal);
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();

        close();
    }

    private void close() {
        loginHandler.close();
    }

    private void open() {
        loginHandler = new LoginDBAdapter(this);
        loginHandler.open();
    }

    public void onClick(View v) {
        String username = insertUsername.getText().toString();
        String name = insertName.getText().toString();
        String password = insertPassword.getText().toString();
        String confirm = insertFinal.getText().toString();

        //Validation for the fields
        // check if any of the fields are vaccant
        if (username.equals("") || password.equals("") || confirm.equals("")) {
            Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_LONG).show();
            return;
        }
        // check if both password matches
        if (!password.equals(confirm)) {
            Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
            return;
        } else {
            // Save the Data in Database

            loginHandler.register(username, name, password);
            Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
            finish();
        }
    }
}

LoginAdapter。

public class LoginDBAdapter {

    private SQLiteDatabase db;
    private DataBaseHelper myHelp;

    // Labels table name
    public static final String TABLE_NAME = "Users";
    private static final String DATABASE_NAME = "login.db";

    // Labels Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_Username = "Username";
    public static final String KEY_name = "Name";
    public static final String KEY_password = "Password";

    // property help us to keep data
    public int User_id;
    public String Username;
    public String Name;
    public String Password;

    public static final String DATABASE_CREATE = "create table "+ TABLE_NAME+
        "("  + KEY_ID + " integer primary key autoincrement ,"
        + KEY_Username + "Username text not null, "
        + KEY_name + "Name text not null, "
        + KEY_password +"Password text not null);";

    private final Context context;
    public LoginDBAdapter(Context data) {
        this.context = data;
        myHelp = new DataBaseHelper(context);
    }

    public LoginDBAdapter open(){
        db = myHelp.getWritableDatabase();
        return this;
    }

    public void close(){
        myHelp.close();
    }

    public long register(String username, String name, String password){

        ContentValues newUser = new ContentValues();

        newUser.put(KEY_Username, username);
        newUser.put(KEY_name, name);
        newUser.put(KEY_password, password);

        //Inserting put information into a new row into Users table
        return db.insert(TABLE_NAME, null, newUser);
    }

    public String authLogin(String username) {
        Cursor cursor = db.query("Users", null, " Username= ?", new String[]{username}, null, null, null);
        if (cursor.getCount() < 1) {
            cursor.close();
            return "Username does not exist";
        }
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex("Password"));
        cursor.close();
        return password;
    }

    private static class DataBaseHelper extends SQLiteOpenHelper {

        private static final int version = 1;
        public DataBaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, version);
        }

        //This is called if no database exists and DataBaseHelper will create a new one

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL("create table "+ TABLE_NAME+
                "("  + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                + KEY_Username + "Username text not null, "
                + KEY_name + "Name text not null, "
                + KEY_password +"Password text not null)");
        }

        // Called when there is a database version mismatch meaning that the version
        // of the database on disk needs to be upgraded to the current version.
        @Override
        public void onUpgrade(SQLiteDatabase create_db, int oldVersion, int newVersion)
        {
            // Log the version upgrade.
            Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
            //Destroy all data
            create_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
            // Create a new one.
            onCreate(create_db);
        }

    }

}

我做错了什么?我让项目在一个点上传递了用户名,名称和密码传递给注册但无法插入表用户,因为它不存在。我通过Android设备监视器

运行它

没有表格:用户

3 个答案:

答案 0 :(得分:0)

您的SQL语句存在问题。

+ KEY_Username + "Username text not null, "

这将呈现为

"UsernameUsername text not null, "

所以你应该把它改成:

+ KEY_Username + " text not null, "

同样的错误也存在于其他方面。

答案 1 :(得分:0)

我认为你从不称呼这种方法

private void open() {
    loginHandler = new LoginDBAdapter(this);
    loginHandler.open();
}
来自Register类的

。 我建议按如下方式更改onCreate方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_register);

    insertUsername = (EditText) findViewById(R.id.insertUsername);
    insertName = (EditText) findViewById(R.id.insertName);
    insertPassword = (EditText) findViewById(R.id.insertPassword);
    insertFinal = (EditText) findViewById(R.id.insertFinal);

    open();
}

答案 2 :(得分:0)

  

使用此代码。它将帮助您在sqlite中创建表,以及您也可以存储注册表详细信息

<强> Register.java

public class Register extends Activity implements View.OnClickListener {

EditText insertUsername, insertName, insertPassword, insertFinal;
Button create;


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_register);

    insertUsername = (EditText) findViewById(R.id.insertUsername);
    insertName = (EditText) findViewById(R.id.insertName);
    insertPassword = (EditText) findViewById(R.id.insertPassword);
    insertFinal = (EditText) findViewById(R.id.insertFinal);
}


public void onClick(View v) {
    String username = insertUsername.getText().toString();
    String name = insertName.getText().toString();
    String password = insertPassword.getText().toString();
    String confirm = insertFinal.getText().toString();

    //Validation for the fields
    // check if any of the fields are vaccant
    if (username.equals("") || password.equals("") || confirm.equals("")) {
        Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_LONG).show();
        return;
    }
    // check if both password matches
    if (!password.equals(confirm)) {

        Toast.makeText(getApplicationContext(),  "Password does not match", Toast.LENGTH_LONG).show();
        return;
    } else {
        // Save the Data in Database


       Intent intent1=new Intent(Register.this,LoginDBAdapter.class);
            Bundle userdata=new Bundle();
            userdata.putString("username",username);
            userdata.putString("name",name);
            userdata.putString("password",password);
            userdata.putString("confirm",confirm );
            intent1.putExtras(userdata);
            startActivity(intent1);

        Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();

    }
}

}

<强> LoginDBAdapter.java

public class LoginDBAdapter extends Activity {

TextView text;
 SQLiteDatabase mydb;
 String username,name,password;
    private static String DBNAME = "login.db";    // THIS IS THE SQLITE DATABASE FILE NAME.
    private static String TABLE = "Users";  
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Bundle userdetails=getIntent().getExtras();
   username= userdetails.getString("username");
    name=userdetails.getString("name");
    password=userdetails.getString("password");
     text=(TextView)findViewById(R.id.txthead);


    createTable();  
    insertIntoTable(username,name,password);
}
public void createTable(){
    try
    {
    mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
    mydb.execSQL("CREATE TABLE IF  NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, Username TEXT,Name TEXT, Password TEXT);");
    mydb.close();
    }
    catch(Exception e)
    {
        Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
    }
}
@SuppressLint("DefaultLocale")
public void onsearchclick(View view)
{


   // Toast.makeText(getApplicationContext(), "subval of"+ subval+""+subval1+"",Toast.LENGTH_SHORT).show();
    showTableValues();



}

public void insertIntoTable(String username,String name,String password){
    try{
        mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
        mydb.execSQL("INSERT INTO " + TABLE + "(Username,Name,Password) VALUES('"+username+"','"+name+"','"+password+"')");

       mydb.close();
    }
    catch(Exception e)
    {

     Toast.makeText(getApplicationContext(), ""+e.toString()+"", Toast.LENGTH_LONG).show();
     //System.out.println(""+e.toString()+"");
    }
}

showTableValues将显示最后输入的用户名和密码以及该人的姓名

public void showTableValues()
{
    try
    {
        mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);

        Cursor cursor=mydb.rawQuery("SELECT * FROM Users", null);      
        int x = cursor.getCount(); //this will return number of records in current cursor
       Toast.makeText(getApplicationContext(), ""+x+"",Toast.LENGTH_SHORT).show();
        if ( x == 0 )
        {
            //No rows are inserted in table
        } 
        else 
        {

            try 
            {
                cursor.moveToFirst();
                 do {
                     String username=cursor.getString(cursor.getColumnIndex("Username")).toString();
                     String name=cursor.getString(cursor.getColumnIndex("Name")).toString();
                     String password=cursor.getString(cursor.getColumnIndex("Password")).toString();



                    String tempString="User Name:  "+username.toString();
                    String tempString1="Name: "+""+name.toString();
                     String tempString2="Password: "+""+password.toString();

                     TextView text=(TextView)findViewById(R.id.txthead);
               text.setText(tempString);
                    text.append(tempString1);
                    text.append(tempString2);

                   } while (cursor.moveToNext());
                }
                finally 
                {
                cursor.close();
                mydb.close();
                }

                // }
            }
       }
    catch( Exception e)
            {

                Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();

            }

        }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
  //  getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

<强> fragment_register.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<EditText
    android:id="@+id/insertFinal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/final1"
    android:layout_alignBottom="@+id/final1"
    android:layout_alignParentRight="true"
    android:ems="10"
    android:hint="Confirm Password" >


</EditText>

<EditText
    android:id="@+id/insertUsername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:ems="10"
    android:hint="Enter user name" />

<TextView
    android:id="@+id/txtusername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/insertUsername"
    android:layout_alignBottom="@+id/insertUsername"
    android:layout_alignParentLeft="true"
    android:text="User Name:" />

<Button
    android:id="@+id/Register"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="125dp"
    android:padding="30dp"
    android:text="Register" 
    android:onClick="onClick"/>

<TextView
    android:id="@+id/final1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/Register"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="78dp"
    android:text="Confirm password" />

<TextView
    android:id="@+id/Password"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/insertFinal"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="17dp"
    android:text="Password" />

<EditText
    android:id="@+id/insertPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/Password"
    android:layout_alignBottom="@+id/Password"
    android:layout_alignParentRight="true"
    android:ems="10"
    android:hint="enter password" />

<EditText
    android:id="@+id/insertName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/insertPassword"
    android:layout_alignParentRight="true"
    android:ems="10"
    android:hint="Enter Name:" />


<TextView
    android:id="@+id/txtname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/txtusername"
    android:layout_alignTop="@+id/insertName"
    android:text="Name:" />

</RelativeLayout>

<强> activity_register.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="show"
        android:onClick="onsearchclick" ></Button>

    <TextView
        android:id="@+id/txthead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/show"    />



</RelativeLayout>
Androidmanifest.xml中的

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.login"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Register"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.login.LoginDBAdapter" />
    </application>

</manifest>