i have two class one is MainActivity.java and DBadapter.java
Main Activity looks like this Code:
public class MainActivity extends Activity {
DBadapter myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
openDB();
populateListFromDB();
}
private void onDistroy(){
super.onDestroy();
closeDB();
}
private void openDB(){
myDB = new DBadapter(this);
myDB.open();
}
public void closeDB(){
myDB.close();
}
private void populateListFromDB(){
Cursor cursor = myDB.getAllRows();
startManagingCursor(cursor);
String[] columnFromTable = new String[]
{DBadapter.KEY_NAME, DBadapter.KEY_GAMES, DBadapter.KEY_WON,
DBadapter.KEY_LOST, DBadapter.KEY_DIFF, DBadapter.KEY_POINTS};
int[] toLayoutElement = new int[]
{R.id.txtview_name, R.id.txtview_gameno, R.id.txtview_won,
R.id.txtview_lost, R.id.txtview_difference, R.id.txtview_points};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(
this, R.layout.item_layout, cursor, columnFromTable, toLayoutElement);
ListView mylistview = (ListView) findViewById(R.id.listview_tabela);
mylistview.setAdapter(myCursorAdapter);
}
}
and the DBadapter Code:
public class DBadapter {
private static final String TAG = "DBadapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "name";
public static final String KEY_GAMES = "games_no";
public static final String KEY_WON = "won";
public static final String KEY_LOST= "lost";
public static final String KEY_DIFF="difference";
public static final String KEY_POINTS="points";
public static final int COL_NAME = 1;
public static final int COL_GAMES = 2;
public static final int COL_WON = 3;
public static final int COL_LOST= 4;
public static final int COL_DIFF= 5;
public static final int COL_POINTS= 6;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_GAMES, KEY_WON, KEY_LOST, KEY_DIFF, KEY_POINTS};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "mydaatabase";
public static final String DATABASE_TABLE = "baske_tbl";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_GAMES + " integer not null, "
+ KEY_WON + " integer not null"
+ KEY_LOST + " integer not null, "
+ KEY_DIFF + " integer not null, "
+ KEY_POINTS + " integer not null "
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
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();
}
// 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;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase database, 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:
database.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(database);
}
}
}
also have two layouts one is row layout called item_layout.xml and list_activity.xml with listView in it.
every time i try to run it it shows "process has stopped unexpectedly". Any solution ?
Related
I am building a simple bank app (no security what so ever) and have a login activity that verifies the input with an SQLite database. My method returns 1 if is a match and 0 if not. The problem is it always returns 0 because the database is null according to debug. I'm not sure why the variable I use in the login method is null. The data insert is working as I've checked using SQLite browser.
Here is the SQLite database with the login() method at the bottom:
public class CustomerDatabase{
private SQLiteDatabase database;
private SQLiteOpenHelper openHelper;
//Database constants
public static final String DB_Name = "customers.db";
public static final int DB_Version = 1;
public static final String CUSTOMER_TABLE = "Customers";
public static final String CARD_ACCESS_NO = "accessNo";
public static final int CARD_ACCESS_NO_COLUMN = 0;
public static final String CUSTOMER_PASSWORD = "password";
public static final int CUSTOMER_PASSWORD_COLUMN = 2;
public static final String CUSTOMER_NAME = "custName";
public static final int CUSTOMER_NAME_COLUMN = 1;
public static final String CHECKING_ACCOUNT_FUNDS = "checkAccFunds";
public static final int CHECKING_ACCOUNT_FUNDS_COLUMN = 3;
public static final String SAVINGS_ACCOUNT_FUNDS = "saveAccFunds";
public static final int SAVINGS_ACCOUNT_FUNDS_COLUMN = 4;
public static final String CHECKING_ACCOUNT_NO = "checkAccNo";
public static final int CHECKING_ACCOUNT_NO_COLUMN = 5;
public static final String SAVINGS_ACCOUNT_NO = "saveAccNo";
public static final int SAVINGS_ACCOUNT_NO_COLUMN = 6;
//DDL for creating the db
public static final String CREATE_CUSTOMER_TABLE =
"CREATE TABLE " + CUSTOMER_TABLE + " (" +
CARD_ACCESS_NO + " INTEGER PRIMARY KEY, " +
CUSTOMER_NAME + " TEXT, " +
CHECKING_ACCOUNT_NO + " TEXT, " +
CUSTOMER_PASSWORD + " TEXT, " +
CHECKING_ACCOUNT_FUNDS + " TEXT, " +
SAVINGS_ACCOUNT_NO + " TEXT, " +
SAVINGS_ACCOUNT_FUNDS + " TEXT)";
public CustomerDatabase(Context context){
openHelper = new DBHelper(context, DB_Name, DB_Version);
}
//method to store accountHolder objects into the database
public AccountHolder saveAccHolder(AccountHolder holder){
database = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CARD_ACCESS_NO, holder.getAccessCardNo());
values.put(CUSTOMER_NAME, holder.getName());
values.put(CUSTOMER_PASSWORD, holder.getPassword());
values.put(CHECKING_ACCOUNT_FUNDS, holder.getCheckingAccountFunds());
values.put(CHECKING_ACCOUNT_NO, holder.getCheckingAccountNo());
values.put(SAVINGS_ACCOUNT_NO, holder.getSavingsAccountNo());
values.put(SAVINGS_ACCOUNT_FUNDS, holder.getSavingsAccountFunds());
long id = database.insert(CUSTOMER_TABLE, null, values);
holder.setDbId(id);
database.close();
return holder;
}
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context, String name, int version){
super(context, name, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + CUSTOMER_TABLE);
db.execSQL(CREATE_CUSTOMER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
db.execSQL("DROP TABLE IF EXISTS " + CUSTOMER_TABLE);
onCreate(db);
}
}
/**Method will be used by the bank to check if user is authorized */
public int login(String accessNo, String password){
String[] selectArgs = new String[]{accessNo,password};
try{
int i = 0;
Cursor cursor = null;
cursor = database.rawQuery("SELECT * FROM CUSTOMER_TABLE WHERE accessNo =? AND password=?",selectArgs);
cursor.moveToFirst();
i = cursor.getCount();
cursor.close();
return i;
}
catch (Exception e){ e.printStackTrace();}
return 0;
}
}
Debug says that the database variable is null at login() at line cursor = database.rawQuery()...
Here is the login activity logic:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtAccessCardNo.length() != 0 || edtPassword.length() != 0){
String accessNoInput = edtAccessCardNo.getText().toString();
String passwordInput = edtPassword.getText().toString();
boolean checkVerify = isVerifiedUser(accessNoInput, passwordInput);
if(checkVerify){
Intent intent = new Intent(getApplicationContext(), BankActivity.class);
startActivity(intent);
}else{
txtErrorDisplay.setText("Unable to login.");
}
}else{
edtAccessCardNo.setHint("This is a required field");
edtPassword.setHint("This is a required field");
}
}
});
}
//Method to create dummy accountHolder objects
public void getAndSaveDummyHolders(){
CustomerDatabase custDb = new CustomerDatabase(this);
for(int i = 0; i < 5; i++){
AccountHolder holder = new AccountHolder(
holderNames[i], accessNo[i],
passwords[i], checkAccNo[i], savAccNo[i],
checkAccFunds[i], savAccFunds[i]);
custDb.saveAccHolder(holder);
}
}
//verify the user using method in customer database
public boolean isVerifiedUser(String userAccessCard, String userPassword){
CustomerDatabase custDb = new CustomerDatabase(getApplicationContext());
int check = custDb.login(userAccessCard, userPassword);
if(check == 1){
return true;
}else{
return false;
}
}
I saw this tutorial: https://www.youtube.com/watch?v=gaOsl2TtMHs
but it seem that when i see the activity there isn't any item listview :\
What can be the problem? I put my code under below
The Main Activity.java
public class Prova2 extends Activity {
int[] imageIDs = {
R.drawable.spaghettiscoglio,
R.drawable.abbacchioascottadito,
R.drawable.agnellocacioeova,
R.drawable.agnolotti,
R.drawable.alettedipollo,
R.drawable.amaretti,
R.drawable.anatraarancia,
R.drawable.alberinatale
};
int nextImageIndex = 0;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prova2);
openDB();
populateListViewFromDB();
registerListClickCallback();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
public void onClick_AddRecord(View v) {
int imageId = imageIDs[nextImageIndex];
nextImageIndex = (nextImageIndex + 1) % imageIDs.length;
// Add it to the DB and re-draw the ListView
myDb.insertRow("Jenny" + nextImageIndex, imageId, "Green");
populateListViewFromDB();
}
public void onClick_ClearAll(View v) {
myDb.deleteAll();
populateListViewFromDB();
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM, DBAdapter.KEY_FAVCOLOUR, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.tvFruitPrice, R.id.ivFruit, R.id.tvFruitPrice, R.id.smalltext};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.sis, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
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);
displayToastForId(idInDB);
}
});
}
private void updateItemForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
favColour += "!";
myDb.updateRow(idInDB, name, studentNum, favColour);
}
cursor.close();
populateListViewFromDB();
}
private void displayToastForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
String message = "ID: " + idDB + "\n"
+ "Name: " + name + "\n"
+ "Std#: " + studentNum + "\n"
+ "FavColour: " + favColour;
Toast.makeText(Prova2.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
The DBAdaptor.java
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_STUDENTNUM = "studentnum";
public static final String KEY_FAVCOLOUR = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_STUDENTNUM = 2;
public static final int COL_FAVCOLOUR = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_STUDENTNUM, KEY_FAVCOLOUR};
// 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_STUDENTNUM + " integer not null, "
+ KEY_FAVCOLOUR + " 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, int 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_STUDENTNUM, studentNum);
initialValues.put(KEY_FAVCOLOUR, 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 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_STUDENTNUM, studentNum);
newValues.put(KEY_FAVCOLOUR, 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);
}
}
I have a problem with the following issue:
I have build an Android app which saves data into a SQL database (SQLite). I managed so the current date, time and the category is saved down and shown in a different menu. Somehow I am not able to get the value saved down and shown in the other layout. The data should come from an EditText: android:id="#+id/edit_betrag
The SQL column is defined like: public static final String BUDGET_BETRAG = "betrag";
and then should be shown in textView_betrag in the class BudgetRechnerAdapter respectively the other layout.
Can you please help me with this issue? Thanks a lot!!!
public class BudgetRechnerOpenHandler extends SQLiteOpenHelper {
private static final String TAG = BudgetRechnerOpenHandler.class
.getSimpleName();
// Name und Version der Datenbank
private static final String DATABASE_NAME = "budgetrechner.db";
private static final int DATABASE_VERSION = 1;
// Name und Attribute der Tabelle "Budget"
public static final String _ID = "_id";
public static final String TABELLE_NAME_BUDGET = "budget";
public static final String BUDGET_ZEIT = "zeitStempel";
public static final String BUDGET_AUSGABENART = "ausgabenArt";
public static final String BUDGET_BETRAG = "betrag";
// Konstanten für die Stimmungen
public static final int BUDGET_ESSEN = 1;
public static final int BUDGET_GETRAENK = 2;
public static final int BUDGET_SONSTIGES = 3;
// Tabelle Budget anlegen
private static final String TABELLE_BUDGET_ERSTELLEN = "CREATE TABLE "
+ TABELLE_NAME_BUDGET + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + BUDGET_ZEIT + " INTEGER, "
+ BUDGET_BETRAG + " INTEGER," + BUDGET_AUSGABENART + " INTEGER);";
// Tabelle Budget löschen
private static final String TABELLE_BUDGET_DROP = "DROP TABLE IF EXISTS "
+ TABELLE_NAME_BUDGET;
BudgetRechnerOpenHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABELLE_BUDGET_ERSTELLEN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrade der Datenbank von Version " + oldVersion + " zu "
+ newVersion + "; alle Daten werden gelöscht");
db.execSQL(TABELLE_BUDGET_DROP);
onCreate(db);
}
public void insert(int art, String beschreibung, long zeit) {
long rowId = -1;
try {
// Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
// die zu speichernden Werte
ContentValues wert = new ContentValues();
wert.put(BUDGET_AUSGABENART, art);
wert.put(BUDGET_BETRAG, beschreibung);
wert.put(BUDGET_ZEIT, zeit);
// in die Tabelle Budget einfügen
rowId = db.insert(TABELLE_NAME_BUDGET, null, wert);
} catch (SQLiteException e) {
Log.e(TAG, "insert()", e);
} finally {
Log.d(TAG, "insert(): rowId=" + rowId);
}
}
public Cursor query() {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
return db.query(TABELLE_NAME_BUDGET, null, null, null, null, null,
BUDGET_ZEIT + " DESC"
);
}
public void update(long id, int ausgabe_art_zahl) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BUDGET_AUSGABENART, ausgabe_art_zahl);
int numUpdated = db.update(TABELLE_NAME_BUDGET, values, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "update(): id=" + id + " -> " + numUpdated);
}
public void delete(long id) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
int numDeleted = db.delete(TABELLE_NAME_BUDGET, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "delete(): id=" + id + " -> " + numDeleted);
}
}
public class BudgetRechnerAdapter extends CursorAdapter {
private final Date datum;
private static final DateFormat DF_DATE = SimpleDateFormat
.getDateInstance(DateFormat.MEDIUM);
private static final DateFormat DF_TIME = SimpleDateFormat
.getTimeInstance(DateFormat.MEDIUM);
private Integer betrag;
private static final Integer DF_BETRAG = R.id.edit_betrag;
private LayoutInflater inflator;
private int ciAusgabenArt, ciZeit, ciBetrag;
public BudgetRechnerAdapter(Context context, Cursor c) {
super(context, c);
datum = new Date();
betrag = null;
inflator = LayoutInflater.from(context);
ciAusgabenArt = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_AUSGABENART);
ciZeit = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_ZEIT);
ciBetrag = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_BETRAG);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView image = (ImageView) view.findViewById(R.id.icon);
int art = cursor.getInt(ciAusgabenArt);
TextView textView_art = (TextView) view.findViewById(R.id.text3);
if (art == BudgetRechnerOpenHandler.BUDGET_ESSEN) {
image.setImageResource(R.drawable.bild_essen);
textView_art.setText("Essen");
} else if (art == BudgetRechnerOpenHandler.BUDGET_GETRAENK) {
image.setImageResource(R.drawable.bild_getraenk);
textView_art.setText("Getränk");
} else {
image.setImageResource(R.drawable.bild_sonstiges);
textView_art.setText("Sonstiges");
}
TextView textView_Datum = (TextView) view.findViewById(R.id.text1);
TextView textView_Zeit = (TextView) view.findViewById(R.id.text2);
TextView textView_betrag = (TextView) view.findViewById(R.id.text4);
long zeitStempel = cursor.getLong(ciZeit);
datum.setTime(zeitStempel);
textView_Datum.setText(DF_DATE.format(datum));
textView_Zeit.setText(DF_TIME.format(datum));
textView_betrag.setText(DF_BETRAG.toString());
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflator.inflate(R.layout.verlauf, null);
}
}
I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
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;
public class DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.
I am using SQLite in Android eclipse, however it gives me a java.lang.nullpointerexception in the function createEntry. I tried using Questoid SQLite manager to view the database file and it does show up with the table created. Where's the bug?
public class Transact {
public static final String KEY_ROWID = "_id";
public static final String KEY_TAG = "saved_tag";
private static final String DATABASE_NAME = "MyDatabaseName";
private static final String DATABASE_TABLE = "tagsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TAG + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Transact(Context c ){
ourContext = c;
}
public Transact open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String tagword) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TAG, tagword);
return ourDatabase.insert(DATABASE_TABLE, "", cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_TAG};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTag = c.getColumnIndex(KEY_TAG);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iTag) + "\n";
}
return null;
}
}
Code for the add button from Main.java class:
case R.id.addDB:
boolean doneAdd = true;
try{
String tag = textTag.getText().toString();
Transact entry = new Transact(Main.this);
entry.open();
entry.createEntry(tag);
entry.close();
}catch(Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
doneAdd = false;
}finally{
if(doneAdd){
Dialog d = new Dialog(this);
d.setTitle("Addition done");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
You are using ourDatabase variable without initializing it. So not only insert you will get nullpointerexception everywhere where you are using ourDatabase variable
you can use something like following in constructor.
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
used this code in sq light java file
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
Cursor cursor;
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 2;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
public static final String KEY_CONTENT4 = "Content4";
public static final String KEY_CONTENT5 = "Content5";
public static final String KEY_CONTENT6 = "Content6";
public static final String KEY_CONTENT7 = "Content7";
public static final String KEY_CONTENT8 = "Content8";
public static final String KEY_CONTENT9 = "Content9";
public static final String KEY_CONTENT10 = "Content10";
public static final String KEY_CONTENT11 = "Content11";
public static final String KEY_CONTENT12 = "Content12";
// create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_CONTENT1
+ " text not null, " + KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + " text not null, " + KEY_CONTENT4
+ " text not null, " + KEY_CONTENT5 + " text not null, "
+ KEY_CONTENT6 + " text not null, " + KEY_CONTENT7
+ " text not null, " + KEY_CONTENT8 + " text not null, "
+ KEY_CONTENT9 + " text not null, " + KEY_CONTENT10
+ " text not null, " + KEY_CONTENT11 + " blob not null, "
+ KEY_CONTENT12 + " long not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c) {
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("PRAGMA foreign_keys=ON");
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}