如何从android中的SQLite数据库中获取名称

时间:2014-05-09 13:31:18

标签: java android database sqlite

我正在开发一个Android应用程序,当用户进入应用程序时,第一个活动要求他的名字输入文本字段。通过单击“提交”按钮,用户的名称将存储在SQLite数据库中,并打开另一个活动,并在下一个活动中显示该用户的名称。现在,我想要这样的东西,如果用户关闭应用程序并且当他再次启动它时,则不应该再次询问用户的名字,他应该直接转到他第一次输入的名字的第二个活动。这是我的完整代码:

DatabaseHandler.java

import java.util.ArrayList;
import java.util.List;

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.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper 
{
    private static final int DATABASE_VERSION=1;
    private static final String DATABASE_NAME="Database1";// Database Name...       
    private static final String TABLE_NAME = "Name"; // Name of the Table...
    private static final String KEY_ID = "id"; // Column1 of the table
    private static final String KEY_NAME="UserName";// Column2 of the table


    private static final String DATABASE_CREATE = "create table "
              + TABLE_NAME + "(" + KEY_ID   
              + " integer primary key autoincrement, " + KEY_NAME
              + " text not null);";


    public DatabaseHandler(Context context)         
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        db.execSQL(DATABASE_CREATE);
    }


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

    public void addName(Name name)
    {
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(KEY_NAME, name.getUsername());
        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public Name getName(int id)
    {
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.query(TABLE_NAME, new String[]{ KEY_ID,KEY_NAME },KEY_ID +"=?",new String[] { String.valueOf(id) },null,null,null,null);
        if(cursor!=null)
        {
            cursor.moveToFirst();
        }
        Name name = new Name(Integer.parseInt(cursor.getString(0)),cursor.getString(1));
        return name;
    }

    public List<Name> getAllNames() {
        List<Name> nameList = new ArrayList<Name>();

        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Name name = new Name();
                name.setId(Integer.parseInt(cursor.getString(0)));
                name.setUsername(cursor.getString(1));
                // Adding contact to list
                nameList.add(name);
            } while (cursor.moveToNext());
        }
        return nameList;
    }

}

MainActivity.java

import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;

public class MainActivity extends Activity 
{
    Button submit;
    EditText et1;

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

        submit=(Button)findViewById(R.id.button1);

        et1=(EditText)findViewById(R.id.editText1);
        final DatabaseHandler db = new DatabaseHandler(this);

        submit.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v1) 
            {
                if(v1==submit)
                {
                    String name1=et1.getText().toString();
                    Log.d("Insert: ", "Inserting .."); 
                     db.addName(new Name(et1.getText().toString())); 
                     Log.d("Reading: ", "Reading all contacts.."); 
                     List<Name> names = db.getAllNames(); 

                     for (Name n : names) {
                            String log = "Id: "+n.getId()+" ,Name: " + n.getUsername();
                        Log.d("Name: ", log);
                    }
                    Intent i1=new Intent(getApplicationContext(),NextPage.class);
                    i1.putExtra("name",name1);
                    startActivity(i1); 
                }

            }
        });


    }

    @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) 
    {

        return super.onOptionsItemSelected(item);
    }

}

main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.database.MainActivity$PlaceholderFragment" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="62dp"
        android:ems="10"
        android:hint="Please Enter Your Name"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:text=" Submit " />

</RelativeLayout>

我对此怎么做不知道。请帮助我......

2 个答案:

答案 0 :(得分:1)

您可以使用共享首选项而不是SQLte数据库。仅存储名称共享首选项就足够了 因此,当您的应用程序启动时,您只需检查特定的共享首选项是否包含用户名,如果不是,则询问用户该名称。

SharedPreferences settings = getSharedPreferences("PREFERENCES", MODE_PRIVATE);
if(settings.getString("USER_NAME", "").equals("")) {
    //User has to enter the name
    //Do the specific action
    String user_name = ...
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("USER_NAME", user_name);
    editor.commit();
}

答案 1 :(得分:0)

在添加之前,您必须检查数据库中是否已存在名称。改为:

submit.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v1)  {
        if(v1==submit) {
            if( db.db.getAllNames() != null ) {
                // Go directly to intent
            } else {
                // Ask a name
            }
    } );
}