Check if data was written in SQLite Database - java

I want to save the Score from a Quiz in a SQLite Database and change an image in another activity if the Score is 5. There is no error shown, but even if I score 5 the image won't change... How can I log the content of my database to check if the score was added or how can I find the mistake?
DB Helper:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "CE";
public static final String SCORE_TABLE = "score";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public static final String COLUMN_MARKERID = "MARKERID";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase= db;
String create_query = "CREATE TABLE IF NOT EXITS " + SCORE_TABLE + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SCORE + " INTEGER, "
+ COLUMN_MARKERID + " TEXT) ";
db.execSQL(create_query);
}
public void addScore (DbHelper dbh, Integer score, String markerID) {
dbase = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_SCORE, score);
cv.put(COLUMN_MARKERID, markerID);
dbase.insert(SCORE_TABLE, null, cv);
}
public Cursor getScore(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
return cursor;
}
Write the Score into the Database after completing the Quiz:
public class ResultActivity extends Activity {
String markerID;
int score;
TextView t=(TextView)findViewById(R.id.textResult);
Button saveButton = (Button) findViewById(R.id.saveButton);
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
markerID = b.getString("markerID");
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DbHelper dbh = new DbHelper(context);
dbh.addScore(dbh,score,markerID);
Intent intent = new Intent(ResultActivity.this, Discover.class);
intent.putExtra("MarkerID", markerID);
startActivity(intent);
}
});
}
Discover class -> Check if score is 5 and change image if:
DbHelper dbh = new DbHelper(context);
Cursor cursor = dbh.getScore(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(0))== 5 && InfoUeberschrift.toString().equals(cursor.getString(1))){
ImageDone.setImageResource(R.drawable.markerdone);
}
}
while(cursor.moveToNext());
}
cursor.close();
}

The SQLiteDatabase insert function returns a long value, so if an error has occurred it returns -1.
'the row ID of the newly inserted row, or -1 if an error occurred'
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This can be used to see if the insert is happening correctly.
Or you can wrap in try and catch and print message like so
try {
//code
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught", ex.getMessage());
return -1;
}
}
When I have issues using Java and SQLite i normally do it directly with the SQLite desktop version using Shell, as I find it easier to test out table design.
Hope this helps

Related

Retrieve Data As String From SQLite Database in Android Studio

I want to save name in the SQLite Database and later in another activity I want to retrieve that name as a String Value. But I am not being able to get data from the database. Help me please. My code is given below,
Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public void onCreate(SQLiteDatabase db) {String createTable =
"CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT, " + COL2 +" TEXT)";
db.execSQL(createTable);}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
MainActivity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
AddData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
}
}
HomeActivity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
}
}
Here, in this home activity i want to get the username as a string but I don't know how to do that. Help me please...
To retrieve data, you run a query that extracts the data into a Cursor. The Cursor will consist of 0-n rows and will have as many columns as defined in the query. You then move through the rows and use the appropriate Cursor get????? methods to get the actual data.
As an example you could add the following method to your DatabaseHelper :-
public String getName(long id) {
String rv = "not found";
SqliteDatabase db = this.getWritableDatabase();
String whereclause = "ID=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COL2));
}
return rv;
}
The above can then be used by String name = mDatabaseHelper.getName(1);.
Note that this assumes that a row with an ID of 1 exists.
Your Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 +" INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT)"; // You have written ID inplace of COL1
public DatabaseHelper(Context context)
{
super(context,DB_NAME,null,1);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(createTable);
}
public boolean insertData(String name) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL2,name);
long result1 = sqLiteDatabase.insert(TABLE_NAME,null,contentValues1);
return result1 != -1;
}
public Cursor viewData()
{
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor ;
String query = "Select * from " +TABLE_NAME;
cursor= sqLiteDatabase.rawQuery(query, null);
return cursor;
}
Your Main Activity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
mDatabaseHelper.insertData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
}
Your Home Activity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
ArrayList<String> listItem;
ArrayAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.listView);
listItem = new ArrayList<>();
viewData1();
}
private void viewData1() {
Cursor cursor = mDatabaseHelper.viewData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
Log.i("message","Data got");
listItem.add(cursor.getString(1)); // Adding data received to a Listview
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
listView.setAdapter(adapter);
}
}
}
check it out this library
it is very easy to implement
https://github.com/wisdomrider/SqliteClosedHelper

Android Studio: app not saving to/reading from database

So my app is a QR Code scanner. Currently it will read a QR code and display it back to user. I want to get it to also save this result to a database and then proceed to read back from it. Currently it does neither of the last two and I'm struggling to figure out which is causing the issue - either saving to the database or reading back from the database.
My Database code is this:
public class Database {
private static final String DATABASE_NAME = "QRCodeScanner";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "codes";
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
"codeid INTEGER PRIMARY KEY AUTOINCREMENT, " +
"code TEXT NOT NULL);";
public Database(Context ctx) {
this.dbContext = ctx;
}
public Database open() throws SQLException {
mDbHelper = new OpenHelper(dbContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean createUser(String code) {
ContentValues initialValues = new ContentValues();
initialValues.put("codes", code);
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
public ArrayList<String[]> fetchUser(String code) throws SQLException {
ArrayList<String[]> myArray = new ArrayList<String[]>();
int pointer = 0;
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"codeid", "code",
}, "code LIKE '%" + code + "%'", null,
null, null, null);
int codeNameColumn = mCursor.getColumnIndex("code");
if (mCursor != null){
if (mCursor.moveToFirst()){
do {
myArray.add(new String[3]);
myArray.get(pointer)[0] = mCursor.getString(codeNameColumn);
pointer++;
} while (mCursor.moveToNext());
} else {
myArray.add(new String[3]);
myArray.get(pointer)[0] = "NO RESULTS";
myArray.get(pointer)[1] = "";
}
}
return myArray;
}
public ArrayList<String[]> selectAll() {
ArrayList<String[]> results = new ArrayList<String[]>();
int counter = 0;
Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "codeid", "codes" }, null, null, null, null, "codeid");
if (cursor.moveToFirst()) {
do {
results.add(new String[3]);
results.get(counter)[0] = cursor.getString(0);
counter++;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return results;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
And my main java code is this.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button Scan;
private ArrayList<String[]> viewall;
private TextView QR_output;
private IntentIntegrator ScanCode;
private ListView lv;
private ArrayList Search = new ArrayList();
ArrayList<String[]> searchResult;
Database dbh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this caused an error on earlier APKs which made the app switch from 17 to 27
setContentView(R.layout.activity_main);
// Defines the Scan button
Scan = findViewById(R.id.Scan);
// defines the output for text
QR_output = findViewById(R.id.QR_Output);
// looks for the user clicking "Scan"
Scan.setOnClickListener(this);
ScanCode = new IntentIntegrator(this);
// Means the scan button will actually do something
Scan.setOnClickListener(this);
lv = findViewById(R.id.list);
dbh = new Database(this);
dbh.open();
}
public void displayAll(View v){
Search.clear();
viewall = dbh.selectAll();
String surname = "", forename = "";
for (int count = 0 ; count < viewall.size() ; count++) {
code = viewall.get(count)[1];
Search.add(surname + ", " + forename);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
Search);
lv.setAdapter(arrayAdapter);
}
// will scan the qr code and reveal its secrets
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
// if an empty QR code gets scanned it returns a message to the user
if (result.getContents() == null) {
Toast.makeText(this, "This QR code is empty.", Toast.LENGTH_LONG).show();
} else try {
// converts the data so it can be displayed
JSONObject obj = new JSONObject(result.getContents());
// this line is busted and does nothing
QR_output.setText(obj.getString("result"));
} catch (JSONException e) {
e.printStackTrace();
String codes = result.getContents();
boolean success = false;
success = dbh.createUser(codes);
// outputs the data to a toast
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onClick(View view) {
// causes the magic to happen (It initiates the scan)
ScanCode.initiateScan();
}
}
Your issue could well be with the line initialValues.put("codes", code); as according to your table definition there is no column called codes, rather the column name appears to be code
As such using initialValues.put("code", code); may well resolve the issue.
Addititional
It is strongly recommended that you define and subsequently use constants throughout your code for all named
items (tables, columns, views trigger etc) and thus the value will always be identical.
e.g.
private static final String DATABASE_NAME = "QRCodeScanner";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "codes";
public static final String COLUMN_CODEID = "codeid"; //<<<<<<<<< example note making public allows the variable to be used elsewhere
public static final String COLUMN_CODE = "code"; //<<<<<<<<<< another example
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_CODEID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //<<<<<<<<<<
COLUMN_CODE + " TEXT NOT NULL);"; //<<<<<<<<<<
........ other code omitted for brevity
public boolean createUser(String code) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_CODE, code); //<<<<<<<<<< CONSTANT USED
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
You would also likely encounter fewer issues by not using hard coded column offsets when extracting data from Cursor by rather using the Cursor getColumnIndex method to provide the offset.
e.g. instead of :-
results.get(counter)[0] = cursor.getString(0);
it would be better to use :-
results.get(counter)[0] = cursor.getString(cursor.getColumnIndex(COLUMN_CODEID));

ListView does not show items that are stored in an SQLite database

I just implemented an SQLite database for a simple to do app for persistence. However, the problem is that when I restart the app, I do not have my data that is stored in an SQLite database. The following is my SQLite helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final String TABLE_NAME = "student";
public static final String ID = "id";
public static final String TO_DO = "todo";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TO_DO_TABLE = "CREATE TABLE "
+ TABLE_NAME
+ "("
+ ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TO_DO
+ " TEXT"
+ ")";
sqLiteDatabase.execSQL(CREATE_TO_DO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String todo){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
return true;
}
}
And in my MainActivity.java, I'm adding my List items into the database as well as the ListView.
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
private final int REQUEST_CODE = 10;
ArrayList <String> toDoItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ListView listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = (ListView) findViewById(R.id.listViewItems);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, toDoItems);
listItems.setAdapter(adapter);
databaseHelper = new DatabaseHelper(this);
...
}
public void addItem(View v){
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
String item = newItem.getText().toString();
databaseHelper.insertData(item);
adapter.add(item);
newItem.setText("");
}
}
I believe I need to do something in the onCreate method but my addItem(View v) method is called through the button onClick.
as #cristian_franco said, the toDoItems is empty yet. What you need to do is to create another method in DatabaseHelper class like this.
public ArrayList<String> showStudents(){
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0)+" "+cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
and then assign toDoItems like this
databaseHelper = new DatabaseHelper(this);
toDoItems=databaseHelper.showStudents();
Let me know if there is any mistake in my code.
implment this function for get the values,
public void getDatos(){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from student",null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex("todo"));
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
cursor.moveToNext();
}
}
}
yout funciion for save is correct only you need get the information

SQlite delete function is not deleting entries

Im having trouble getting individual items to delete in a database my application is using. I know the method gets called, but nothing in my list is ever removed. Im not getting any errors which is making it tough to track down. Assistance would be awesome.
public class MainActivity extends Activity{
//Global Variables
ListView lv;
Intent addM, viewM;
public DBAdapter movieDatabase;
String tempTitle, tempYear;
int request_Code = 1;
int request_code2 = 2;
SimpleCursorAdapter dataAdapter;
Cursor cursor;
Button addButton;
long testID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creates the database
movieDatabase = new DBAdapter(this);
movieDatabase.open();
//movieDatabase.deleteAllMovies();
//creates the intents to start the sub activities
addM = new Intent(this, AddMovie.class);
viewM = new Intent(this, MovieView.class);
}
//handles the return of the activity addMovie
public void onActivityResult(int requestCode, int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
switch(requestCode)
{
case 1:
dbAddMovie(data.getStringExtra("title"),
data.getStringExtra("year"));
break;
case 2:
testID = data.getLongExtra("rowid", -1);
dMovie(testID);
break;
}
}
}
//adds item to the movie list
public void dbAddMovie(String mT, String mY)
{
movieDatabase.open();
movieDatabase.insertMovie(mT, mY);
Toast.makeText(this, "Movie: " + mT + " added to database",
Toast.LENGTH_SHORT).show();
}
//deletes an entry into the database
public void dMovie(long rowid)
{
//Toast.makeText(this, "Deleting: " + rowid,
Toast.LENGTH_SHORT).show();
movieDatabase.deleteMovie(rowid);
movieDatabase.getAllMovies();
}
//displays the database as a list
public void displayListView()
{
addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
cursor = movieDatabase.getAllMovies();
//columns to use
String[] columns = new String[]
{
movieDatabase.KEY_TITLE,
};
//xml data to bind the data to
int[] to = new int[]
{
R.id.column2,
};
//adapter to display the database as a list
dataAdapter = new SimpleCursorAdapter(this,
R.layout.complexrow, cursor, columns, to, 0);
//gets the List view resource
lv = (ListView) findViewById(R.id.movielist);
//sets the list view to use the adapter
lv.setAdapter(dataAdapter);
//handles the list click events
lv.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View
v, int position,
long id) {
Cursor cursor = (Cursor)
parent.getItemAtPosition(position);
Bundle mDet = new Bundle();
mDet.putString("title",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_TITLE)));
mDet.putString("year",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_YEAR)));
mDet.putInt("rId", position);
viewM.putExtras(mDet);
startActivityForResult(viewM, 2);
}
});
//dataAdapter.notifyDataSetChanged();
}
public void onResume()
{
super.onResume();
displayListView();
}
}
and my coresponding dbadapter class
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_YEAR = "year";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MovieListDB";
private static final String DATABASE_TABLE = "MoviesTable";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table MoviesTable (_id
integer primary key autoincrement, " +
"title text not null, year not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_CREATE);
} catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion +
"which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS MoviesTable");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insertMovie(String title, String year)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_YEAR, year);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "='" + rowID+"'", null ) >-1;
}
public Cursor getAllMovies()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_YEAR}, null, null, null, null, null);
}
public Cursor getMovie(long rowID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_YEAR}, KEY_ROWID + "=" + rowID, null, null, null, null, null);
if(mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateContact(long rowID, String title, String year)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_YEAR, year);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowID, null) > 0;
}
public void deleteAllMovies() {
int doneDelete = 0;
doneDelete = db.delete(DATABASE_TABLE, null, null);
}
}
You're using the position returned from your listview as the row id in your database. This won't necessarily match up with your autoincremented "_id" in your database. position is just what position in the list it is.
You might want to think about using movieDatabase.KEY_ROWID as the key for your intents. Right now I see a mix of "rowid", "rId", "_id", and KEY_ROWID. It would simplify thing to just use the same key everywhere when referring to the same thing.
It looks like you continuously add bundles to the viewM intent. Is that true? If that's not your intent, you should either create a new intent for each click, or remove the previous bundles first.
I'm assuming KEY_ROWID is actually the name of the column? Try the following:
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[] { String.valueOf(rowID) }) >-1;
}

SimpleCursorAdapter does not load external sqlite database: "_id" error

The error says: column _id does not exists but the column is in the database (set as primary key) and this one is located in the external SD folder. I'm trying to return the values contained in the database on the initial load of the activity but it seems like the cursor is not returning anything.
public class ComponentsDbAdapter {
public static final String COLUMN_ID = "_id";
public static final String COLUMN_SUBSTRUCTURE = "substructure";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_ORDERNUM = "ordernum";
public static final String COLUMN_INSTALLATION = "installation";
private static final String TAG = "ComponentsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/DATABASE_BACKUP/IMPORTED/";
private static final String DATABASE_NAME = "android.db";
private static final String TABLE_NAME = "TAB_WORKSCPE";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
public ComponentsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_PATH+DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public ComponentsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public Cursor fetchComponentsByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null);
} else {
mCursor = mDb.query(true, TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, COLUMN_TYPE + " like '%" + inputText + "%'", null, null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllComponents() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
public class AndroidListViewCursorAdaptorActivity extends Activity {
private ComponentsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbHelper = new ComponentsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllComponents();
// The desired columns to be bound
String[] columns = new String[] {
ComponentsDbAdapter.COLUMN_SUBSTRUCTURE,
ComponentsDbAdapter.COLUMN_TYPE,
ComponentsDbAdapter.COLUMN_ORDERNUM,
ComponentsDbAdapter.COLUMN_INSTALLATION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.inst,
R.id.subdt,
R.id.type,
R.id.ordernum,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this,
R.layout.country_info,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String compSubdt = cursor.getString(cursor.getColumnIndexOrThrow("subdt"));
Toast.makeText(getApplicationContext(), compSubdt, Toast.LENGTH_SHORT).show();
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,int count, int after) {
}
public void onTextChanged(CharSequence s, int start,int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchComponentsByName(constraint.toString());
}
});
}
}
It doesn't appear from your code that you've created the table yet, so no columns will be found.
You do this within the onCreate method by creating a query to create the table. In your code you appear to be doing a select rather than create.
private static final String TABLE_CREATE = "create table "
+ TABLE_NAME
+ "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_TYPE + " text not null default '', "
+ COLUMN_ORDERNUM + " integer not null default 0, "
+ COLUMN_INSTALLATION + " integer not null default 0, "
+ COLUMN_SUBSTRUCTURE + " text not null default ''"
+ ");";
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE);
}
To store this on the external storage, you'll need to override getDatabasePath(...). A similar solution is here https://stackoverflow.com/a/8385537/935779
#Override
public File getDatabasePath(String name) {
// reference where you would like the file to be here.
File result = new File(getExternalFilesDir(null), name);
return result;
}
I believe you'll want to override this with your Application class since it's a member of ContextWrapper.
The method getDatabaseFile(...) is used inside of openOrCreateDatabase(...) to determine the location.
Alternatively you could just override openOrCreateDatabase(...) and set the file location there.
I don't think you can change or even specify the location of the database, only the name.
Leave off the path and don't try to put it in External Storage - let Android determine the path.
Ok, this took me almost week and a lot of stress but here is the solution. I started to go through a lot of tutorials and got it working in this one:
http://www.mysamplecode.com/2012/11/android-database-content-provider.html
I extracted the database from the virtual device and manually added more data. Then copied the database to the desired folder on my device folder (Its just to make sure the database consistency/columns are exactly the same). Then changed MyDatabaseHelper class as follows:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/MYFOLDER/";
private static final String DATABASE_NAME = "TheWorld.db";
private static final int DATABASE_VERSION = 1;
MyDatabaseHelper(Context context) {
super(context, DATABASE_PATH+DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
CountriesDb.onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
CountriesDb.onUpgrade(db, oldVersion, newVersion);
}
}
Don't forget to add permissions to your manifest:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Done!
If you read through the posts above the answer is based on Kirks advice so reading his recommended link helps. I still have more tests to do just in case my database structure was wrong before.

Categories