如何显示名称

时间:2018-05-24 03:43:30

标签: android android-sqlite

如果用户输入名称后如何显示名称,因为我还不知道如何操作并将数据插入数据库。

我想显示名称,并能够添加时间和日期闹钟。

如果用户输入名称后如何显示名称,因为我还不知道如何操作并将数据插入数据库。

我想显示名称,并能够添加时间和日期闹钟。

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private TabLayout tabLayout;
    private AppBarLayout appBarLayout;
    private ViewPager viewPager;
    private EditText edtName;

    Spinner spin1;
    Spinner spin2;
    Spinner spin3;

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

        DBHelper db = new DBHelper(); 


        tabLayout = findViewById(R.id.tablayout);
        appBarLayout = findViewById(R.id.bar);
        viewPager = findViewById(R.id.viewpager);

        edtName = findViewById(R.id.edtName);

        spin1 = findViewById(R.id.spinnerFrequency);
        spin2 = findViewById(R.id.SpinnerTime);
        spin3 = findViewById(R.id.SpinnerQty);

        Adapter adapter = new Adapter(getSupportFragmentManager());
        /*screen*/
        adapter.AddFragment(new Drugfragment(), "Drug");
        adapter.AddFragment(new Appointmentfragment(), "Appointment");

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);




        Account c = new Account();
        if(c==null) {

        }else{
           AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("LOG IN");
            LayoutInflater inflater = MainActivity.this.getLayoutInflater();
            builder.setView(inflater.inflate(R.layout.account,null));
                    builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                    LayoutInflater inflater = MainActivity.this.getLayoutInflater();


                                    builder.setView(inflater.inflate(R.layout.accountname,null));
                                    builder.setPositiveButton("Yes",new DialogInterface.OnClickListener(){
                                        public void onClick(DialogInterface dialog, int id) {

                                        }
                                    });


                                    builder.show();
                                }
                            });



            builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            System.exit(0);
                        }
                    });

            builder.show();

            db.insertRecord();

        }

    }

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String text = parent.getItemAtPosition(position).toString();
        Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


}

这是我的数据库助手

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

/**
 * Created by User on 23/5/2018.
 */

public class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME="accountDB.db";
    private static final String DATABASE_TABLE="Account";
    private static final String COL1="AccountName";
    private static final String COL2="Time";

    public DBHelper(){
        super(context, DATABASE_NAME, null, 1);
    }

    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table Account(acctname text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        this.onCreate(db);
    }

    public void insertRecord(AccountInfo a){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contents = new ContentValues();

        contents.put("AccountName", a.getAcctName());
    }


}

1 个答案:

答案 0 :(得分:0)

检索并使用存储在Android设备上的SQLiteDatabase中的数据的基本原则是使用/运行查询 SELECT 数据,这是可以通过光标,然后在光标内移动到适当的行,最后从相应的列中提取数据。

对于您的特定问题,您希望找到最后插入的行,幸运的是SQLite有一个可以提供帮助的功能,即last_insert_rowid()

因此查询将为SELECT * FROM Account WHERE rowid = last_insert_rowid()

由于您提供的代码存在各种问题。以下是基于您的代码的示例: -

  1. 添加一个新帐户(虽然只是一个名称非常基本的帐户)然后
  2. 提取最后添加的帐户的名称(虽然您知道这个名称根本不是很有用)。

    • 请注意,这是非常有限的,但显示了一种技术。
    • 注意rowid是一个特殊的列,默认情况下为每一行提供(WITHOUT ROWID表没有rowid)。 rowid 唯一标识一行,最初是一个整数1,然后可能是2,然后可能是3 .......但它永远不应该依赖于单调增加。
  3. 首先是一个非常简单的AccountInfo类,即AccountInfo.java(您已经看到它了: -

    public class AccountInfo {
    
        private String mAccountName;
    
        public AccountInfo(String account_name) {
            this.mAccountName = account_name;
        }
        public String getAcctName() {
            return mAccountName;
        }
    }
    

    第二个 DBHelper.java (注意评论,也不是与你的相似之处): -

    public class DBHelper extends SQLiteOpenHelper {
    
        private static final String DATABASE_NAME="accountDB.db";
        private static final String DATABASE_TABLE="Account";
        private static final String COL1="AccountName"; //<<<< not used
        private static final String COL2="Time"; //<<<< not used
    
        public DBHelper(Context context){ //<<<< modifed to include the Context to be passed
            super(context, DATABASE_NAME, null, 1);
        }
    
        //<<<<<<<<<< This is superfluous and isn't used in this example >>>>>>>>>>
        //<<<<<<<<<< It could be deleted                                >>>>>>>>>>
        public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table Account(acctname text)");
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            this.onCreate(db);
        }
    
        public void insertRecord(AccountInfo a){
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contents = new ContentValues();
            //contents.put("AccountName", a.getAcctName()); //<<<< Will fail as incorrect column name
            contents.put("acctname",a.getAcctName()); //<<<< column name as per table definition
            db.insert(DATABASE_TABLE,null,contents); //<<<< ADDED to do the insert itself
        }
    
        //<<<<<<<<<< The Query that gets the name of the account last added >>>>>>>>>>
        public String getLastInsertedAccountName() {
            String rv = ""; //<<<< Just in case nothing is extracted set the return value to empty String
            String[] columns = new String[]{"acctname"}; //<<<< The columns to extract (only one)
            String whereclause = "rowid = last_insert_rowid()"; //<<<< The SQL WHERE clause (less the WHERE keyword)
            SQLiteDatabase db = this.getWritableDatabase();//<<<< Get the SQLite database
            // Use the SQLliteDatabase convenience query method that gets the data into a Cursor
            Cursor csr = db.query(
                    DATABASE_TABLE, //<<<< The table to be queried (ie FROM )
                    columns, //<<<< The columns to be returned just one (could use null to return all columns)
                    whereclause, //<<<< The WHERE clause
                    null, //<<<< selection args (none so null)
                    null, //<<<< the column(s) to GROUP BY (none so null)
                    null, //<<<< The having clause (none so null)
                    null //<<<< The ORDER BY clause (none so null)
            );
            //<<<< Move to the first (only) row in the Cursor (if there is one)
            if (csr.moveToFirst()) {
                // Get the value, as a string, from the column name acctname
                rv = csr.getString(
                        csr.getColumnIndex(
                                "acctname"
                        )
                );
            }
            csr.close(); //<<<< Close the Cursor as done with it
            return rv; //<<<< Finally retruned that extracted value
        }
    }
    

    活动中的调用代码 MainActivity (非常简单): -

    公共类MainActivity扩展了AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        DBHelper mDBHlpr = new DBHelper(this); //<<<< Get an instance of the DBHelper
        AccountInfo c = new AccountInfo("Fred"); //<<<< Create an Account to add
        mDBHlpr.insertRecord(c);
        //<<<<<<<<<< one line version of the two lines above (commented out) <<<<<<<<<<
        //mDBHlpr.insertRecord(new AccountInfo("Tom"));
    
        String account_just_inserted = mDBHlpr.getLastInsertedAccountName(); //<<<< get the name
    
        //<<<<<<<<<< Do something with the name i.e. write it out to the Log >>>>>>>>>>
        Log.d(
                "ACCOUNT INSERTED",
                "The Name of the account just inserted is :-" +
                        account_just_inserted
        );
    }
    

    }

    • 注意每次运行应用时,都会添加一个新行,并将添加Fred作为帐户名。

    结果

    运行上面的内容将输出类似于: -

    的内容
    05-24 09:27:14.215 1287-1287/acnta.accountapp D/ACCOUNT INSERTED: The Name of the account just inserted is :-Fred