I'm having a problem with my code. I don't know how to check multiple columns in the database to insert different data on every not existing data.
For example:
1st input
Name: Raymond Jay Berin
Event: INTRAMURALS
FACILITATOR: CSG
2nd input
Name: Raymond Jay Berin
Event: LOVE SYMPOSIUM
FACILITATOR: DSSC
the thing here is that. Raymond Jay Berin already existed in the database, but I want Raymond Jay Berin will be inserted into a different event...
also, I already tried to create multiple tables but my project crashes when I click the attendance button to add data.
Code for DatabaseHelper.class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.sqlite";
public static final String TABLE_NAME = "attendance";
public static final String COL_1 = "ID";
public static final String COL_2 = "FULLNAME";
public static final String COL_EVENT_2 = "EVENT_NAME";
public static final String COL_EVENT_3 = "FACILITATOR_NAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
//ATTENDANCE
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FULLNAME TEXT NOT NULL, EVENT_NAME TEXT NOT NULL, FACILITATOR_NAME TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//ATTENDANCE
db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME );
//recreate
onCreate(db);
}
//ATTENDANCE
public boolean insertData (String fullname, String event, String facilitator){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,fullname);
contentValues.put(COL_EVENT_2,event);
contentValues.put(COL_EVENT_3,facilitator);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean checkIfRecordExist(String nameOfTable,String columnName,String columnValue) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT "+columnName+" FROM "+nameOfTable+" WHERE "+columnName+"='"+columnValue+"'",null);
if (cursor.moveToFirst()) {
db.close();
Log.d("Record Already Exists", "Table is:" + nameOfTable + " ColumnName:" + columnName);
return true;//record Exists
}
Log.d("New Record ", "Table is:" + nameOfTable + " ColumnName:" + columnName + " Column Value:" + columnValue);
db.close();
} catch (Exception errorException) {
Log.d("Exception occured", "Exception occured " + errorException);
db.close();
}
return false;
} }
Code for the Attendance.java class
public class Attendance extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DatabaseHelper myDb;
EditText fname , eventname, faciname;
Button attendance;
Button view;
Switch lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
myDb = new DatabaseHelper(this);
fname = findViewById(R.id.txtFullname);
eventname = findViewById(R.id.eventname);
faciname = findViewById(R.id.faciname);
attendance = findViewById(R.id.btnatt);
view = findViewById(R.id.btnview);
lock = findViewById(R.id.switchLock);
viewAll();
AddData();
lock.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (lock.isChecked()){
eventname.setEnabled(false);
faciname.setEnabled(false);
}else{
eventname.setEnabled(true);
faciname.setEnabled(true);
}
}
public void viewAll() {
view.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show message
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("EVENT :" + res.getString(2) + "\n");
buffer.append("FACILITATOR :" + res.getString(3) + "\n"+"\n");
}
// Show all data
showMessage("ATTENDANCE LIST", 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();
}
public void AddData() {
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String valInput = fname.getText().toString();
final String valInput1 = eventname.getText().toString();
final String valInput2 = faciname.getText().toString();
boolean valid = true;
if (TextUtils.isEmpty(valInput)) {
fname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput1)) {
eventname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput2)) {
faciname.setError("This Item must not be empty!");
valid = false;
}
if (valid) {
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString());
if (!isExist) {
boolean isInserted = myDb.insertData(fname.getText().toString(), eventname.getText().toString(), faciname.getText().toString());
if (isInserted) {
Toast.makeText(Attendance.this, "Attendance Success", Toast.LENGTH_LONG).show();
fname.setText(null);
} else if (isInserted == false) {
Toast.makeText(Attendance.this, "Failed to Attendance", Toast.LENGTH_LONG).show();
}
}else if (isExist == true){
Toast.makeText(Attendance.this, "Failed to Attendance "+fname+" Already Existed", Toast.LENGTH_LONG).show();
}
}
}
}); }
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.Logout)
.setMessage(R.string.really_logout)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = new Intent(Attendance.this, MainActivity.class);
startActivity(intent);
Attendance.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}}
change checkIfRecordExist method like this
public boolean checkIfRecordExist(String nameOfTable,String columnName1,String columnValue1,String columnName2,String columnValue2) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+nameOfTable+" WHERE "+columnName1+"='"+columnValue1+"' and "+ columnName2 +"='"+columnValue2+"'",null);
.......................
change below line like this
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString(),DatabaseHelper.COL_2, eventname.getText().toString())
Related
I want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 + " TEXT" + COL3 + " ,TEXT)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am new in Java Programming.
Now, I am facing the problem that I want to change the shared preferences and want to use the SQLite database to store these data. I had created the table for store these data and I am trying to save these data in SQLite.
How can I do? Anyone can help me ????
MyDatabase-Table
This is my code that using shared preferences :
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
reg = new AC_Class.Register();
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
// Check preferences/create if nonexistent
prefs = this.getSharedPreferences("com.presoft.androidmobilestock", Context.MODE_PRIVATE);
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
prefs.edit().putString("UUID", uniqueID).commit();
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
finish();
}
//On return of intent
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 7) {
url = data.getStringExtra("URLKey");
urlStr = data.getStringExtra("URLStr");
Log.i("custDebug", url + ", " + urlStr);
binding.txtURL.setText(urlStr);
if (!TextUtils.isEmpty(binding.txtURL.getText().toString())) {
new GetModules(Login.this).execute(url);
new GetLoginList(Login.this).execute(url);
new SetDevice(Login.this).execute(url);
}
}
}
//Open connection settings
public void btnSetClicked(View view) {
Intent intent = new Intent(Login.this, ConnectionSettings.class);
startActivityForResult(intent, 7);
}
//Reset Database
public void btnResetDbClicked(final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Reset DB");
builder.setMessage("Are you sure you want to reset the Database?");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().toString().equals("presoftmobile")) {
db.close();
deleteDatabase("AutoCountDatabase");
} else {
// Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//Login button
public void btnLoginBtnClicked(View view) {
if (TextUtils.isEmpty(binding.txtURL.getText().toString())) {
binding.txtURL.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtID.getText().toString())) {
binding.txtID.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtpw.getText().toString())) {
binding.txtpw.setError("This field can't be blank.");
//return;
}
//Non-empty fields
else {
Cursor checkData = db.loginValidate(binding.txtID.getText().toString(),
binding.txtpw.getText().toString().toUpperCase());
if (checkData.getCount() > 0) {
checkData.moveToNext();
//Shared Preferences
prefs.edit().putString("URL", url).apply();
prefs.edit().putString("URLstr", binding.txtURL.getText().toString()).apply();
if (binding.rmbCheckBox.isChecked()) {
prefs.edit().putString("ID", binding.txtID.getText().toString()).apply();
prefs.edit().putString("pwd", binding.txtpw.getText().toString()).apply();
}
prefs.edit().putInt("EnableSetting", checkData.getInt(checkData.getColumnIndex("EnableSetting"))).apply();
prefs.edit().putInt("FilterByAgent", checkData.getInt(checkData.getColumnIndex("FilterByAgent"))).apply();
prefs.edit().putInt("Sales", checkData.getInt(checkData.getColumnIndex("Sales"))).apply();
prefs.edit().putInt("Purchase", checkData.getInt(checkData.getColumnIndex("Purchase"))).apply();
prefs.edit().putInt("Transfer", checkData.getInt(checkData.getColumnIndex("Transfer"))).apply();
if (url != null) {
try {
// Check Connection
new SetDevice(Login.this).execute(url);
// Go to main
Intent intent = new Intent(Login.this, Dashboard.class);
intent.putExtra("URLKey", url);
intent.putExtra("URLStr", binding.txtURL.getText().toString());
startActivity(intent);
finish();
} catch (Exception e) {
Log.i("custDebug", e.getMessage());
Toast.makeText(this, "Unable to connect to server", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show();
binding.txtpw.setText(null);
}
checkData.close();
}
}
This is the code that to save the data in SQLite database (but getting error):
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
db = new ACDatabase(this);
uniqueID = db.getReg("8");
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
db.updateREG("8", uniqueID);
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
mydatabasehelper
//GET value by id
public Cursor getReg(String id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT Value FROM " + TABLE_NAME_REG + " WHERE ID ='" + id + "'",null);
return data;
}
//update value
public boolean updateREG(String ID, String Value) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Value", Value);
String[] args = new String[]{ID};
database.update("Reg", cv, "ID = ?", args);
return true;
}
The following is a working example that acts very similar to shared prefs but stores the prefs in an SQLite database.
The table is very simple 2 columns. The key (name of the stored value) and the value itself. Which can be String, boolean, int, long or Float.
It includes methods to; insert (add) a key/value pair, update a key/value pair and to get a value according to the key and also to return a default value as passed (making it easy to detect if the value was retrieved).
The DatabaseHelper (sub class of SQLiteOpenHelper) has most of the code and is :-
class DBHelper extends SQLiteOpenHelper {
private static volatile DBHelper instance = null;
private SQLiteDatabase db = null;
public static final String DBNAME = "sharedpreferences.db";
public static final int DBVERSION = 1;
public static final String TBLNAME_SP = "_shared_preferences";
public static final String COLNAME_SP_KEY = "_key";
public static final String COLNAME_SP_VALUE = "_value";
private DBHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TBLNAME_SP +
"(" +
COLNAME_SP_KEY + " PRIMARY KEY," +
COLNAME_SP_VALUE + " TEXT" +
")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private long insertPrefsRow(ContentValues cv, String key) {
cv.put(COLNAME_SP_KEY,key);
return db.insertWithOnConflict(TBLNAME_SP,null,cv, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertPrefsValue (String key, int value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, String value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, long value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, boolean value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, float value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
private long updatePrefs(String key, ContentValues cv) {
return db.update(TBLNAME_SP,cv,COLNAME_SP_KEY + "=?",new String[]{key} );
}
public long updatePrefsStringValue(String key, String newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, boolean newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, int newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, long newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, Float newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
private Cursor getPrefsValue(String key) {
return db.query(TBLNAME_SP,new String[]{COLNAME_SP_VALUE},COLNAME_SP_KEY + "=?",new String[]{key},null,null,null);
}
public String getPrefsStringValue(String key, String default_value) {
String rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Boolean getPrefsBooleanValue(String key, boolean default_value ) {
Boolean rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE)) != 0;
csr.close();
}
return rv;
}
public int getPrefsIntValue(String key, int default_value) {
int rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public long getPrefsLongValue(String key, long default_value) {
long rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Float getPrefsFLoatValue(String key, Float default_value) {
Float rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getFloat(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
}
The following is an activity that demonstrates usage:-
public class MainActivity extends AppCompatActivity {
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = DBHelper.getInstance(this);
db.insertPrefsValue("UUID","3FDE9813F93A47CBA6CD4F5DAAECEE01");
db.insertPrefsValue("taxInclusive",false);
db.insertPrefsValue("myprefs_int",100);
db.insertPrefsValue("myprefs_long",100L);
db.insertPrefsValue("myprefs_float",10.567F);
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
db.updatePrefsStringValue("UUID","FFFF9813F93A47CBA6CD4F5DAAECEE01");
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
}
}
When run (or rerun BUT when rerun the updated UUID rather than the original is retrieved) the log contains :-
D/PREFSINFO: Stored UUID is 3FDE9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
D/PREFSINFO: Stored UUID is FFFF9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
NOT STORED demonstrates the default value being returned when the Key/Name isn't stored.
As you can see UUID has been updated in the second line (if rerun both lines would show the updated value)
I cant't get all data to display in button when click on button get. please help me.
public class DBHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String DATABASE = "Test";
private static final String TABLE_NAME = "savedata";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_SEX = "sex";
public DBHelper(Context context) {
super(context, DATABASE, null,VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " +TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_SEX + " TEXT)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" +TABLE_NAME);
onCreate(db);
}
public void Insertdata(Data data){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, data.getName());
values.put(KEY_SEX, data.getSex());
db.insert(TABLE_NAME, null, values);
}
public List<Data> getAllData(){
List<Data> listData = new ArrayList<Data>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " +TABLE_NAME, null);
if (c.moveToFirst()){
do {
Data data = new Data();
data.setId(c.getInt(0));
data.setName(c.getString(1));
data.setSex(c.getString(2));
listData.add(data);
}while (c.moveToNext());
}
return listData;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
SaveData();
getData();
}
public void SaveData(){
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void getData(){
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
You've messed up badly. That's all I can suggest-
1. Create a class (for example "MyClass") that will extend AppCompatActivity and contains the view.
2. You've already created a class named DBHelper for your Database manipulation. It extends SQLiteOpenHelper.
3. Create object of DBHelper class inside the onCreate method of MyClass and access your database. onCreate method in MyClass will be looking similar to this-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
Hope that, this might help.
I am new to android, I am trying to retrieve values from a sqlite database based on the listview values. I tried to retrieve values using string variable. I can do this if I directly substitute the value in the place of variable.
Following this I post my codes kindly help me to sort out this.
DBhelper.java
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "VERIFY ME1.sqlite3";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "FORM2";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
Oninsert(DB);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
}
else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +tableName +" (AppNo VARCHAR, AppName VARCHAR," +
" Area VARCHAR, FHcode INT(3));");
}}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void Oninsert(SQLiteDatabase dB2) {
// TODO Auto-generated method stub
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("INSERT INTO " +
tableName +
" Values ('M001','shumi','India',250);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C002','sarah','India',251);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D003','Lavya','USA',252);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('V004','Avi','EU',253);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('T005','Shenoi','Bangla',254);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('L006','Lamha','Australia',255);");
DB.close();
}
}
ListActivity.java
public class login2 extends ListActivity implements OnItemClickListener {
private static final login2 ListActivity = null;
private static final AdapterView<?> parent = null;
private static int mPosition = 0;
private static final long id = 0;
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
private String AppName1,ApplID,FHcode,Area;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(this);
}
private String openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " +tableName +"", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
AppName1 = c.getString(c.getColumnIndex("AppName"));
results.add(AppName1 );
}while (c.moveToNext());
}
}
c.close();
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
// newDB.execSQL("DELETE FROM " + tableName);
//newDB.close();
}
return AppName1;
}
public void onClick(View arg0) {
login2 det = (login2)ListActivity;
det.onItemClick(parent, arg0, mPosition, id);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String data=(String)parent.getItemAtPosition(position);
//showMessage("Successfully", data);
if (data != null ) {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c1 = newDB.rawQuery("SELECT DISTINCT AppNo, AppName, FHcode, Area FROM "
+tableName +" where AppName ="+data+"" ,null);
if (c1 != null ) {
if (c1.moveToFirst()) {
do {
ApplID= c1.getString(c1.getColumnIndex("AppNo"));
String AppName =c1.getString(c1.getColumnIndex("AppName"));
Area = c1.getString(c1.getColumnIndex("Area"));
FHcode =c1.getString(c1.getColumnIndex("FHcode"));
Intent intent = new Intent(getApplicationContext(), form.class);
//Create a bundle object
Bundle b = new Bundle();
//Inserts a String value into the mapping of this Bundle
b.putString("AppName", AppName.toString());
b.putString("Apprefno", ApplID.toString());
b.putString("FHcode", FHcode.toString());
b.putString("Area", Area.toString());
//Add the bundle to the intent.
intent.putExtras(b);
//start the DisplayActivity
startActivity(intent);
}
while (c1.moveToNext());
}
}
}
catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
//newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
public void showMessage (String title, String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
You have taken this column as an integer FHcode INT(3)
and trying to fetch values as an string that is wrong
c1.getString(c1.getColumnIndex("FHcode")
change to c1.getInt**(c1.getColumnIndex("FHcode")
here is the LogCat
I can't post image so i put it in google drive
link here
////////And here is the DB///////
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;
public class UserDB {
public static final String TABLE_USER = "User";
public static final String ID = "ID";
public static final String USERNAME = "USERNAME";
public static final String PASSWORD = "PASSWORD";
public static final String CHKPASSWORD = "CHKPASSWORD";
public static final String SEX = "SEX";
public static final String eat = "eat";
public static final String drink = "drink";
public static final String smoke = "smoke";
public static final String conctrolweigh = "conctrolweigh";
public static final String blosuger = "blosuger";
public static final String hospital = "hospital";
private Context Context = null;
public static final String Education = "Education";
public static class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "diabetes.db";
private static final int DATABASE_VERSION = 1;
//usertable
public DatabaseHelper(Context context, CursorFactory factory) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public static final String TABLE_USER_CREATE =
"CREATE TABLE " + TABLE_USER
+ "("
+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ USERNAME + " text , "
+ PASSWORD+ " text ,"
+ CHKPASSWORD+ " text ,"
+ SEX+ " text ,"
+ eat + " text , "
+ drink + " text, "
+ smoke + " text, "
+ conctrolweigh + " text, "
+ blosuger + " text, "
+ hospital + " text, "
+ Education + " text);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
// 每次成功打開資料庫後首先被執行
}
#Override
public synchronized void close() {
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_USER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROPB TABLE IF EXISTS " + TABLE_USER);
onCreate(db);
}
}
public DatabaseHelper dbHelper;
public SQLiteDatabase db;
public UserDB(Context context){
this.Context = context;
DatabaseHelper openHelper = new DatabaseHelper(this.Context);
this.db = openHelper.getWritableDatabase();
}
public UserDB open() throws SQLException{
dbHelper = new DatabaseHelper(Context);
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
//add user
public void insertEntry(String ID, String PWD,String CHPW,String SEX,String eat,String drink,String smoke,String conctrolweigh,String blosuger,String hospital,String Education){
if (PWD.equals(CHPW)){
ContentValues newValues = new ContentValues();
newValues.put("USERNAME", ID);
newValues.put("PASSWORD", PWD);
newValues.put("CHKPASSWORD", CHPW);
newValues.put("SEX", SEX);
newValues.put("eat", eat);
newValues.put("drink", drink);
newValues.put("smoke", smoke);
newValues.put("conctrolweigh", conctrolweigh);
newValues.put("blosuger", blosuger);
newValues.put("hospital", hospital);
newValues.put("Education", Education);
db.insert(TABLE_USER, null, newValues);
}else{
}
}
public String getSinlgeEntry(String userName) {
Cursor cursor = db.query("User", null, " USERNAME=?",
new String[] { userName }, null, null, null);
if (cursor.getCount() < 1) // UserName Not Exist
return "Not Exist";
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
return password;
}
public SQLiteDatabase getReadableDatabase() {
// TODO Auto-generated method stub
return null;
}
}
//////here is the Activity//////////
public class SelfteachingActivity extends Activity {
Button btnselback,tvartical ,tvfood,tvhealth,tvexcise;
TextView tvid,tvstore,tveat,tvhospital,tvblosuger,tvconctrolweigh,tvdrink,tvsmoke,tvSEX,tvEducation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selfteaching);
findViews();
setListeners();
//openDatabase();
String username= (this.getIntent().getExtras().getString("username"));
tvstore.setText(username);
tvid.setText(tvstore.getText().toString());
query();
}
private void query() {
UserDB helper = new UserDB(this);
SQLiteDatabase db = helper.getReadableDatabase();
helper.open();
if(helper.getReadableDatabase() == null){
Log.i("Log Activity Test", "helper is null!!!!!!!!!");
}
String user = tvstore.getText().toString();
try {
Log.i("Log Activity Test", "start db!!");
Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);
if(cursor!=null){
int rows_num = cursor.getCount();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Integer Id = cursor.getInt(cursor.getColumnIndex("id"));
tvSEX.setText(cursor.getString(cursor.getColumnIndex("SEX")));
tvhospital.setText(cursor.getString(cursor.getColumnIndex("hospital")));
tvblosuger.setText(cursor.getString(cursor.getColumnIndex("blosuger")));
tvdrink.setText(cursor.getString(cursor.getColumnIndex("drink")));
tvconctrolweigh.setText(cursor.getString(cursor.getColumnIndex("conctrolweigh")));
tvsmoke.setText(cursor.getString(cursor.getColumnIndex("smoke")));
tvEducation.setText(cursor.getString(cursor.getColumnIndex("Education")));
tveat.setText(cursor.getString(cursor.getColumnIndex("eat")));
cursor.moveToNext();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
}
private long exitTime = 0;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
if((System.currentTimeMillis()-exitTime) > 2000){
Toast.makeText(getApplicationContext(), "再按一次返回鍵退出", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void findViews(){
btnselback = (Button)findViewById(R.id.buttonselback);
tvartical = (Button)findViewById(R.id.buttonartical);
tvfood = (Button)findViewById(R.id.buttonfood);
tvhealth = (Button)findViewById(R.id.buttonhealth);
tvexcise = (Button)findViewById(R.id.buttonescise);
tvid = (TextView)findViewById(R.id.tVsid);
tvstore = (TextView)findViewById(R.id.tvstore);
tveat = (TextView)findViewById(R.id.tveat);
tvhospital= (TextView)findViewById(R.id.tvhospital);
tvblosuger= (TextView)findViewById(R.id.tvblosuger);
tvconctrolweigh= (TextView)findViewById(R.id.tvconctrolweigh);
tvdrink= (TextView)findViewById(R.id.tvdrink);
tvsmoke= (TextView)findViewById(R.id.tvsmoke);
tvSEX= (TextView)findViewById(R.id.tvSEX);
tvEducation= (TextView)findViewById(R.id.tvEducation);
}
private void setListeners(){
//回上一頁
btnselback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, LoginActivity.class);
intent.putExtra("username", username );
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//衛教文章
tvartical.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, ArticalActivity.class);
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("username", username );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//食物衛教
tvfood.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, FoodActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//健康衛教
tvhealth.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, HealthActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//運動衛教
tvexcise.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, ExciseActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.selfteaching, menu);
return true;
}
}
Problem:
1.i don't get any data from SQL but no crash
what is the problem with my code?
the program stop in here
Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);
and say null pointer , i check the db and is null , i don't know how this happen.
plz help me
Method that you call
SQLiteDatabase db = helper.getReadableDatabase();
returns your null due to your code:
public SQLiteDatabase getReadableDatabase() {
// TODO Auto-generated method stub
return null;
}