Hello I want to implement a simple survey. I successfully added the questions with an insert query. The Questions however get added every time when I run the application.
I tried to use "Drop table if exists" but nothing happens.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME= "Questionpool.db";
public static final String createdb = "Create table dtaquestions( questionId Integer Primary Key Autoincrement, dtaQuestion Varchar(100), dtaDepartment Varchar(100))";
public static final String dropdb = "Drop table if exists dtaquestions";
Context context;
public DatabaseHelper(Context context) {
super(context, DBNAME , null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createdb);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(dropdb);
}
And in the Survey class I have this,
myDb = new DatabaseHelper(this);
SQLiteDatabase DB2=myDb.getWritableDatabase();
insertQuestions(DB2);
final Cursor res = getAllData(DB2);
bViewAll = (Button) findViewById(R.id.bViewAll);
bViewAll.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
if(res.getCount()== 0){
tv.setText("nooo");
}else{
int counter = 0;
while(res.moveToNext()){
//show on screen
}
}
}
});
public void insertQuestions(SQLiteDatabase db){
String [] dtaQuestions = fillArray();
String [] dtaQuestionsDep = fillDepartment();
for (int i = 0 ; i < 18 ; i++ ){
ContentValues cv = new ContentValues();
cv.put("dtaQuestion", dtaQuestions[i]);
cv.put("dtaDepartment", dtaQuestionsDep[i]);
db.insert("dtaquestions", null, cv);
}
}
public Cursor getAllData(SQLiteDatabase db){
Cursor res = db.rawQuery("Select * from dtaquestions", null);
return res;
}
I have no idea why the drop query isn't working and the query keeps repeating itself.
Read de cocumentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.
When you create the helper the version is always 1.
super(context, DBNAME , null, 1);
You need to change the version.
You can declare the version and then use it:
private static final int VERSION=2;
public DatabaseHelper(Context context) {
super(context, DBNAME , null,VERSION);
this.context = context;
}
Related
Hello as the title says I cannot get the app to construct a small local sqlite database. I would appreciate some help as I m an amateur. Thanks in advance.
Below there are some pictures of my source code.
I tested this code on level 24 API device, but the database does not appear in the data/data/the_package/databases/ folder
Edited to include code
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CrdDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new CrdDBHelper(this);
boolean p1 = true;
int p11sc = 0;
int p12sc = 0;
Button btnMenu = (Button) findViewById(R.id.btnMenu);
Button btntrue = (Button) findViewById(R.id.btnTrue);
Button btnFalse = (Button) findViewById(R.id.btnFalse);
// All other available code commented out
}
#Override
protected void onDestroy() {
mydb.close();
super.onDestroy();
}
}
CrdDBContract.java
public final class CrdDBContract {
private CrdDBContract(){}
public static final class GameEntry implements BaseColumns {
public static final String TABLE_NAME = "Game";
public static final String COLUMN_KNOWN = "Known";
public static final String COLUMN_TBF = "TBF";
public static final String SQL_CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ _ID + " INTEGER PRIMARY KEY, "
+ COLUMN_KNOWN + " TEXT NOT NULL, "
+ COLUMN_TBF + " TEXT NOT NULL)";
}
}
CrdDBHelper.java
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
CrdDBDataInsertion.java
public class CrdDBDataInsertion {
//??????????? Code not available from images
SQLiteDatabase mDB;
private void contentvalues(String Known, String TBF) {
ContentValues values = new ContentValues();
values.put(CrdDBContract.GameEntry.COLUMN_KNOWN,Known);
values.put(CrdDBContract.GameEntry.COLUMN_TBF,TBF);
long newid = mDB.insert(CrdDBContract.GameEntry.TABLE_NAME,null,values);
}
}
Main Activity part1Main Activity part2
Main Activity part3(final)
DB Contract class
DB Helper class
DB insert class part1
DB insert class part2 (final)
You aren't, according to the code, acessing(opening) the database. You are just instantiating the DatabseHelper in MainActivity i.e. mydb = new CrdDBHelper(this);
It is not until an attempt is made to open the database (which is frequently implicit) that the database is actually created.
A simple way would be to force an open when instantiating the database. e.g. call the getWritableDatabase() method in the constructor, like :-
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getWritableDatabase();
}
Perhaps at that time set an SQLiteDatabase object with the returned SQLiteDatabase, so your Database Helper (CrdDBHelper.java) could be :-
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase mDB;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mDB = this.getWriteableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
as the onCreate method is called when (and ONLY when) the database is created the Game table will then be created.
I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}
what i am trying do is create a table then insert some values into it then and select.
The problem i am facing is the app is unfortunately stopping.I don't know what is the problem.
My code is:
This class calls the database handler
public class SaveEvents extends Activity {
private static final String DB_NAME = "EventDB";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
Bundle extras=getIntent().getExtras();
String event=extras.getString("event");
String date=extras.getString("date");
String college=extras.getString("college");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.insert_data(event,date,college);
String c=db.select_data();
Toast.makeText(getApplicationContext(), "EventName: "+c+"", Toast.LENGTH_LONG).show();
}
}
Database Handler
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "EventDB";
private static final String TABLE_NAME = "eventlist";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_ITEM_TABLE;
CREATE_ITEM_TABLE = "CREATE TABLE eventlist(eventname varchar(100),eventdate varchar(100),college varchar(100));";
db.execSQL(CREATE_ITEM_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
void insert_data(String eventname,String date,String college)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("eventname", eventname);
values.put("eventdate",date);
values.put("college",college);
db.insert(TABLE_NAME,null,values);
db.close();
}
public String select_data()
{
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT eventname FROM eventlist where eventname='techcontest'";
String c=null;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
c=cursor.getString(0);
return c;
}
}
My logcat shows
03-16 20:00:19.116 8378-8378/com.example.android E/SQLiteLog﹕ (1) no such table: eventlist
03-16 20:00:19.122 8378-8378/com.example.android E/SQLiteDatabase﹕ Error inserting college=acs university eventdate=2-02-15 eventname=techocontest
android.database.sqlite.SQLiteException: no such table: eventlist (code 1): , while compiling: INSERT INTO eventlist(college,eventdate,eventname) VALUES (?,?,?)
It doesn't look like you are closing the database in the select_data() method.
I am trying to add a simple int count which is set to count++ everytime a player wins it will increment by 1. I am trying to add this int count inside my SQLite Database. But I have no Idea how I can do that, the database is in one class, and my int value is in another class, How can I add the int inside the database. I have created a addScores method inside my class:
Database Code:
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "number_of_wins";
private static final String DATABASE_NAME = "HIGHSCORES";
private static final String DATABASE_TABLE= "Total_Wins";
private static final int DATABASE_VERSION = 2;
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) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Database(Context context) {
ourContext = context;
}
public Database open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public Cursor getScores() {
return ourDatabase.rawQuery("SELECT * FROM "+DATABASE_TABLE, null); //No Parameter
}
}
Someother Class:
int count =0;
count++;
//Adding HighScore to Database
public void addScore() {
}
How do I add the int count inside my database? I am trying to add it in the column number_of_wins?
You need to insert a value in the database using something like this.
ContentValues values = new ContentValues();
values.put("number_of_wins", counter);
id = ourDatabase.insertOrThrow("Total_Wins", null, values);
Create a method in your database class and add/modify this code, and finally call this new method from 'SomeOther' class.
This is a simple DBHelper that should work for you and get you started, create an instance of this and you should be able to add a score into your database, However I highly recommend you read the tutorial in comment, and really figure out how it works. So from here you should be able to complete all other CRUD operations.
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME= "HIGHSCORES";
private static final String DATABASE_TABLE = "TotalWins";
// The keys
private static final String KEY_ID = "id";
private static final String KEY_SCORE = "NumberOfWins";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY, " +
KEY_SCORE + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Careful with this!
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public void addScore(int score) {
// Get a writable database handle
SQLiteDatabase db = getWritableDatabase();
// Put the coun into a ContentValues object, with correct key
ContentValues values = new ContentValues();
values.put(KEY_SCORE, score);
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
// Closing database connection
db.close();
}
}
I assume you have the unique id for the particular count you'd like to increase. In that case, I'd write the following method inside of the Database class and call it when the count should increase.
public void addScore(long id) {
ourDatabase.execSQL(String.format("UPDATE %s SET %s=%s+1 WHERE %s=%d",
DATABASE_TABLE, KEY_NAME, KEY_NAME, KEY_ID, id));
}
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.