Cant Find Database file in Eclipse for Android - java

I have been doing an android database application project recently.When i tried to execute. I cant find the folder 'databases' in the file explorer of the DDMS. I checked the following path /data/data/packagename/databases,but there i could not find databases folder and my database file.
I have attached the code for database helper class
please help me if there is any error that is preventing me from creating the database or is it wrong with my eclipse. Because even some of my existing projects also don't show up with the databases folder inside them.
DBclass.java:
package pack.andyxdb;
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.SQLiteOpenHelper;
import android.util.Log;
public class DBclass {
public static final String KEY_TIMESTAMP = "Timestamp";
public static final String KEY_UNIQUEID = "UniqueID";
public static final String KEY_DEVICETYPE = "Devicetype";
public static final String KEY_RSSI = "RSSI";
private static final String DATABASE_NAME = "DannyZ.db";
private static final String DATABASE_TABLE = "Data";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;
private static final String USER_MASTER_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
+ KEY_TIMESTAMP + " INTEGER ,"
+ KEY_UNIQUEID + " INTEGER, " + KEY_DEVICETYPE + " TEXT, " + KEY_RSSI + " INTEGER PRIMARY KEY )";
//CREATE TABLE `DannyZ` (
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_MASTER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if DATABASE VERSION changes
// Drop old tables and call super.onCreate()
}
}
public DBclass(Context c) {
ourContext = c;
dbh = new DbHelper(ourContext);
}
public DBclass open() throws SQLException {
odb = dbh.getWritableDatabase();
return this;
}
public void close() {
dbh.close();
}
public long insertrecord(int timestamp, int uniqueID,String Device, int RSSI) throws SQLException{
// Log.d("", col1);
// Log.d("", col2);
ContentValues IV = new ContentValues();
IV.put(KEY_TIMESTAMP, timestamp);
IV.put(KEY_UNIQUEID, uniqueID );
IV.put(KEY_DEVICETYPE, Device != "");
IV.put(KEY_RSSI, RSSI );
return odb.insert(DATABASE_TABLE, null, IV);
// returns a number >0 if inserting data is successful
}
public void updateRow(long rowID, String col1, String col2,String col3,String col4) {
ContentValues values = new ContentValues();
values.put(KEY_TIMESTAMP, col1);
values.put(KEY_UNIQUEID, col2);
values.put(KEY_DEVICETYPE, col3);
values.put(KEY_RSSI, col4);
try {
odb.update(DATABASE_TABLE, values, KEY_RSSI + "=" + rowID, null);
} catch (Exception e) {
}
}
public boolean delete() {
return odb.delete(DATABASE_TABLE, null, null) > 0;
}
public Cursor getAllTitles() {
// using simple SQL query
return odb.rawQuery("select * from " + DATABASE_TABLE + "ORDER BY "+KEY_RSSI, null);
}
public Cursor getallCols(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID, KEY_DEVICETYPE, KEY_RSSI }, null, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
public Cursor getColsById(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID,KEY_DEVICETYPE }, KEY_RSSI + " = " + id, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
}
also my MainActivity.java code is here. Here i try to insert the data into database by making use of submit button. When i hit submit button the app does not stay for long time and says unfortunately myapp has stopped.my curious concern has been is my database being created or not?
please do help me thanks
MainActivity:
public class MainActivity extends Activity {
private ListView list_lv;
private EditText txt1;
private EditText txt2;
private EditText txt3;
private EditText txt4;
private Button btn1;
private Button btn2;
private DBclass db;
private ArrayList<String> collist_1;
private ArrayList<String> collist_2;
private ArrayList<String> collist_3;
private ArrayList<String> collist_4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collist_1 = new ArrayList<String>();
collist_2 = new ArrayList<String>();
collist_3 = new ArrayList<String>();
collist_4 = new ArrayList<String>();
items();
// getData();
}
private void items() {
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
txt1 = (EditText) findViewById(R.id.editText1);
txt2 = (EditText) findViewById(R.id.editText2);
txt3 = (EditText) findViewById(R.id.editText3);
txt4 = (EditText) findViewById(R.id.editText4);
// list_lv = (ListView) findViewById(R.id.dblist);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//getData();
viewData();
}
private void viewData() {
Intent i = new Intent(MainActivity.this, viewActivity.class);
startActivity(i);
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitData();
}
});
}
protected void submitData() {
int a = Integer.parseInt( txt1.getText().toString());
int b = Integer.parseInt( txt2.getText().toString());
String c = txt3.getText().toString();
int d = Integer.parseInt( txt4.getText().toString());
db = new DBclass(this);
long num = 0;
try {
db.open();
num = db.insertrecord(a, b,c,d);
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Error Duplicate value"+e,2000).show();
} finally {
//getData();
}
if (num > 0)
Toast.makeText(this, "Row number: " + num, 2000).show();
else if (num == -1)
Toast.makeText(this, "Error Duplicate value", 4000).show();
else
Toast.makeText(this, "Error while inserting", 2000).show();
}
}

Create object of helper class in your activity onCreate method for creating the database file in android app
DBclass db=new DBclass(context);
Hope this will help.

Related

SQL Lite Data not being inserted (Android Studio in java)

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!

Total price using rawQuery in android [closed]

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 8 years ago.
Improve this question
I've been trying to get the price value from the database and try to make a grand total. I used the rawQuery but always crashed.I think theres a problem in my rawQuery..i still cant get the total after many times i've tried..
this is the code:
DBAdapter
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;
// ------------------------------------ DBAdapter.java ---------------------------------------------
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_QUANTITY = "studentnum";
public static final String KEY_PRICE = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_QUANTITY = 2;
public static final int COL_PRICE = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_PRICE};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_QUANTITY + " integer not null, "
+ KEY_PRICE + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_QUANTITY, studentNum);
initialValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public Cursor getTotalPrice() {
Cursor c = db.rawQuery("SELECT SUM("+ KEY_PRICE +")from " + DATABASE_TABLE, null);
return c;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_QUANTITY, studentNum);
newValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Listprice:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
/**
* Created by User on 6/2/2015.
*/
public class Listprice extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listprice);
openDB();
TextView textView = (TextView) findViewById(R.id.order90);
TextView textView1 = (TextView) findViewById(R.id.quan90);
TextView textView2 = (TextView) findViewById(R.id.price90);
TextView textView3 = (TextView) findViewById(R.id.totalprice);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newText = extras.getString("firstmessage");
String newText1 = extras.getString("secondmessage");
String newText2 = extras.getString("thirdmessage");
if (newText != null) {
textView.setText(newText);
}
if (newText1 != null) {
textView1.setText(newText1);
}
if (newText2 != null) {
textView2.setText(newText2);
}
}
String num1 = textView.getText().toString().trim();
int num2 = Integer.parseInt(textView1.getText().toString());
int num3 = Integer.parseInt(textView2.getText().toString());
int num4 = num2 * num3;
registerListClickCallBack();
myDb.insertRow(num1, "Quantity = " + num2, ""+num4);
populateListViewFromDB();
Cursor sum=myDb.getTotalPrice();
textView3.setText(""+sum);
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
//Query for the record we just added.
//Use the ID:
startManagingCursor(cursor);
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_QUANTITY, DBAdapter.KEY_PRICE};
int[] toViewIDs = new int[]
{R.id.item_name, R.id.quantities, R.id.pricest};
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void openDB(){
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void closeDB() {
myDb.close();
}
private void registerListClickCallBack() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
}
});
}
private void updateItemForId(final long idInDB) {
final Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Listprice.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
myDb.deleteRow(idInDB);
populateListViewFromDB();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
cursor.close();
populateListViewFromDB();
}
public void clear(View view) {
myDb.deleteAll();
populateListViewFromDB();
}
#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);
}
public void addFood(View view) {
Intent gotofood = new Intent(this, food.class);
startActivity(gotofood);
}
public void addDrinks(View view) {
Intent gotodrinks = new Intent(this, drink.class);
startActivity(gotodrinks);
}
public void gotomainmaenu(View view) {
Intent gotomain = new Intent(this, MainActivity.class);
startActivity(gotomain);
}
}
It sounds like you want the sum of each item's price multiplied by that item's quantity. If so, this should work:
public double getTotalPrice() {
String sql = "select sum(" + KEY_QUANTITY + " * " + KEY_PRICE + ") from "
+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
return cursor.getDouble(0);
}
return 0;
}

Android SQL query nullpointer can't get the data from database

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;
}

Order of list items populated from SQLLite DB is incorrect

I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, int port, int passive) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);

cursor.moveToFirst seems to be skipped

I'm new to Java and just tried to make a database. I managed to make a DB and all but when I want to read the values it seems to get an error.
This is my code for my settings activity (which asks for setting values and add them in the DB on a specific ID)
public class Settings extends Activity{
Button Save;
static Switch SwitchCalculations;
public static String bool;
public static List<Integer> list_id = new ArrayList<Integer>();
public static List<String> list_idname = new ArrayList<String>();
public static List<String> list_kind = new ArrayList<String>();
public static List<String> list_value = new ArrayList<String>();
static Integer[] arr_id;
static String[] arr_idname;
static String[] arr_kind;
static String[] arr_value;
public static final String TAG = "Settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Save = (Button) findViewById(R.id.btnSave);
SwitchCalculations = (Switch) findViewById(R.id.switchCalcOnOff);
readData();
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
writeData();
//Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT).show();
readData();
Save.setText("Opgeslagen");
}
});
}
public void writeData() {
int id = 1;
String idname = "switchCalcOnOff";
String kind = "switch";
boolean val = SwitchCalculations.isChecked();
String value = new Boolean(val).toString();
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dbh.C_ID, id);
cv.put(dbh.C_IDNAME, idname);
cv.put(dbh.C_KIND, kind);
cv.put(dbh.C_VALUE, value);
if (dbh.C_ID.isEmpty() == true) {
db.insert(dbh.TABLE, null, cv);
Log.d(TAG, "Insert: Data has been saved.");
} else if (dbh.C_ID.isEmpty() == false) {
db.update(dbh.TABLE, cv, "n_id='1'", null);
Log.d(TAG, "Update: Data has been saved.");
} else {
Log.d(TAG, "gefaald");
}
db.close();
}
public void readData() {
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
List<String> list_value = new ArrayList<String>();
String[] arr_value;
list_value.clear();
Cursor cursor = db.rawQuery("SELECT " + dbh.C_VALUE + " FROM " + dbh.TABLE + ";", null);
if (cursor.moveToFirst()) {
do {
list_value.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()){
cursor.close();
}
db.close();
arr_value = new String[list_value.size()];
for (int i = 0; i < list_value.size(); i++){
arr_value[i] = list_value.get(i);
}
}
}
Then I have my dbHelper activity see below:
package com.amd.nutrixilium;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbHelper_Settings extends SQLiteOpenHelper{
private static final String TAG="dbHelper_Settings";
public static final String DB_NAME = "settings.db";
public static final int DB_VERSION = 10;
public final String TABLE = "settings";
public final String C_ID = "n_id"; // Special for id
public final String C_IDNAME = "n_idname";
public final String C_KIND = "n_kind";
public final String C_VALUE = "n_value";
Context context;
public dbHelper_Settings(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
// oncreate wordt maar 1malig uitgevoerd per user voor aanmaken van database
#Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format("create table %s (%s int primary key, %s TEXT, %s TEXT, %s TEXT)", TABLE, C_ID, C_IDNAME, C_KIND, C_VALUE);
Log.d(TAG, "onCreate sql: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE); // wist een oudere database versie
Log.d(TAG, "onUpgrate dropped table " + TABLE);
this.onCreate(db);
}
}
And the weird thing is I don't get any error messages here.
But I used Log.d(TAG, text) to check where the script is being skipped and that is at cursor.moveToFirst().
So can anyone help me with this problem?
Here, contrary to what you seem to expect, you actually check that a text constant is not empty:
if (dbh.C_ID.isEmpty() == true) {
It isn't : it always contains "n_id"
I think your intent was to find a record with that id and, depending on the result, either insert or update.
You should do just that: attempt a select via the helper, then insert or update as in the code above.
Edit:
Add to your helper something like this:
public boolean someRowsExist(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("select EXISTS ( select 1 from " + TABLE + " )", new String[] {});
cursor.moveToFirst();
boolean exists = (cursor.getInt(0) == 1);
cursor.close();
return exists;
}
And use it to check if you have any rows in the DB:
if (dbh.someRowsExist(db)) { // instead of (dbh.C_ID.isEmpty() == true) {
Looks like you're having trouble debugging your query. Android provides a handy method DatabaseUtils.dumpCursorToString() that formats the entire Cursor into a String. You can then output the dump to LogCat and see if any rows were actually skipped.

Categories

Resources