SQLite数据库数据检索

时间:2017-06-21 17:18:47

标签: android database sqlite

package com.darkweb.android.amity_v13;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "myapp.db";
public static final int DB_VERSION = 1;

public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "Id";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_MOBILE = "mobile";
public static final String COLUMN_AID = "amizoneid";



/*
create table users(
    id integer primary key autoincrement,
    email text,
    password text);
 */
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
        + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT,"
        + COLUMN_EMAIL + " TEXT,"+ COLUMN_MOBILE + " TEXT,"+ COLUMN_AID + " TEXT,"
        + COLUMN_PASS + " TEXT);";

public DbHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

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

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


public void addUser(String email, String pass,  String _name,String _mobile, String _id) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_EMAIL, String.valueOf(email));
    values.put(COLUMN_PASS, String.valueOf(pass));
    values.put(COLUMN_NAME, String.valueOf(_name));
    values.put(COLUMN_MOBILE, String.valueOf(_mobile));
    values.put(COLUMN_AID, String.valueOf(_id));

    long id = db.insert(USER_TABLE, null, values);
    db.close();

    Log.d(TAG, "user inserted" + id);
}


public boolean getUser(String email, String pass){
    //HashMap<String, String> user = new HashMap<String, String>();
    String selectQuery = "select * from  " + USER_TABLE + " where " +
            COLUMN_EMAIL + " = " + "'"+email+"'" + " and "
            +COLUMN_PASS + " = " + "'"+pass+"'";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        return true;
    }
    cursor.close();
    db.close();

    return false;
}
}

'我刚学习SQLite数据库,我想从我的数据库中检索日期并在活动中将其显示为TextView,该怎么做? 给我代码,以便我能为我的大学项目提供一些帮助!

1 个答案:

答案 0 :(得分:0)

希望它会帮助你

MainActivity.java

public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText sname,sphno,scomment;
Button btnadd;
Button btnviewAll;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myDb=new DatabaseHelper(this);
    sname=(EditText)findViewById(R.id.editText_name);
    sphno=(EditText)findViewById(R.id.editText_phno);
    scomment=(EditText)findViewById(R.id.editText_comment);
    btnadd=(Button)findViewById(R.id.button_adddata);
    btnviewAll=(Button)findViewById(R.id.button_viewall);
    AddData();
    viewAll();
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
public void AddData()
{
    btnadd.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v)
                {
                    boolean isInserted=myDb.insertData(sname.getText().toString(),sphno.getText().toString(),scomment.getText().toString());

                    if(isInserted==true)
                        Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(MainActivity.this,"Not Inserted",Toast.LENGTH_LONG).show();
                }

            }
    );


}
public void viewAll()
{
    btnviewAll.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cursor res=myDb.getAllData();
                    if(res.getCount() == 0)
                    {
                        showMessage("Error","Nothing Found");
                        return;

                    }
                    StringBuffer buffer=new StringBuffer();
                    while(res.moveToNext())
                    {
                        buffer.append("Id: "+res.getString(0)+"\n");
                        buffer.append("Name: "+res.getString(1)+"\n");
                        buffer.append("Phno: "+res.getString(2)+"\n");
                        buffer.append("Comment: "+res.getString(3)+"\n\n");
                        showMessage("Data",buffer.toString());

                    }
                }
            }


    );


}
public void showMessage(String title,String Message)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(Message);
    builder.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.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME="Indb.db";
public static final String TABLE_COMMENTS="students_data";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_PHNO = "phno";
public static final String COLUMN_COMMENT = "comment";


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    SQLiteDatabase db=this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table "
            + TABLE_COMMENTS + "(" + COLUMN_ID
            + " integer primary key autoincrement, " + COLUMN_NAME
            + " text not null, " + COLUMN_PHNO
            + " text not null, " + COLUMN_COMMENT
            + " text not null);");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_COMMENTS);
    onCreate(db);
}
public boolean insertData(String name, String phno, String comment) {
    SQLiteDatabase db = getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_NAME, name);
    contentValues.put(COLUMN_PHNO, phno);
    contentValues.put(COLUMN_COMMENT, comment);
    long result=db.insert(TABLE_COMMENTS, null, contentValues);
    if(result == -1)
        return false;
    else
        return true;
}
public Cursor getAllData()
{

    SQLiteDatabase db = getWritableDatabase();
    Cursor res=db.rawQuery("select * from "+TABLE_COMMENTS,null);
    return res;

}

}