Trouble in retrieving table names from Android SQLite database - android

I want to insert tables in Android SQLite database and then want to show that table names in a listView but after creating tables in database I am unable to retrieve table names from database.
My code of retrieving table names is as follows:
public void updateBranchList()
{
//this method will open database
openDatabase();
String sql = "SELECT name FROM sqlite_temp_master WHERE type='table' ORDER BY name";
Cursor c = db.rawQuery(sql,null);
//branchList is an ArrayList<String>
branchList.clear();
if(c.moveToFirst())
while(!c.isAfterLast())
{
String s = c.getString(c.getColumnIndex("name"));
branchList.add(s);
c.moveToNext();
}
db.close();
}
public void openDatabase()
{
db = openOrCreateDatabase("studentinfo", Context.MODE_PRIVATE,null);
}

The sqlite_temp_master table contains information about tables in the temporary database. For information about tables in the main database, you have to use sqlite_master instead.

Related

Filtering out data for sql android

I have a strings that contains c++ codes.
these codes might contain a single or double inverted quotes and many such thing,
I want to filter out these characters before executing the sql to insert this into the SQLite Database (Android) so, what java code should i run to do that without disturbing/distorting the c++ code, so that when i read the sql database the code should be as before.
You could filter (replace with nothing) when extracting the data using SQL.
e.g. such a query could be :-
SELECT replace(replace(col1,'''',''),'"','') FROM cpluspluscode;
where the respective column is col1 and the table is cpluspluscode.
The following is an example showing how this works:-
DROP TABLE IF EXISTS cpluspluscode;
CREATE TABLE IF NOT EXISTS cpluspluscode (col1 TEXT);
INSERT INTO cpluspluscode VALUES('''mytext'' "other text"');
SELECT * FROM cpluspluscode;
SELECT replace(replace(col1,'''',''),'"','') AS filtered FROM cpluspluscode;
The results from the above are :-
Without filtering :-
Filtered :-
The above takes advantage of the SQLite replace core function replace(X,Y,Z)
Unicode
If you wanted the to do the above using unicode then you could use :-
SELECT replace(replace(col1,char(0034),''),char(39),'') AS filtered FROM cpluspluscode;
This utilises the SQLite char core function (see link above).
The unicode core function can be used to find the unicode for a character (again see link above).
Android Example
Assuming a subclass of SQLiteOpenHelper is DatabaseHelper and this creates the table as per :-
public static final String TABLE_CPLUSPLUSCODE = "cpluspluscode";
public static final String COLUMN1 = "col1";
.........
#Override
public void onCreate(SQLiteDatabase db) {
String crtcpp = "CREATE TABLE IF NOT EXISTS " + TABLE_CPLUSPLUSCODE + "(" +
COLUMN1 + " TEXT" +
")";
db.execSQL(crtcpp);
}
And DatabaseHelper includes the methods :-
public long cppInsert(String value) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN1,value);
return db.insert(TABLE_CPLUSPLUSCODE,null,cv);
}
public Cursor getFiltered() {
SQLiteDatabase db = this.getWritableDatabase();
String[] columns = new String[]{"replace(replace(" + COLUMN1 + ",'''',''),'\"','') AS " + COLUMN1};
return db.query(TABLE_CPLUSPLUSCODE,columns,null,null,null,null,null);
}
public Cursor getUnfiltered() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_CPLUSPLUSCODE,null,null,null,null, null, null);
}
Then using the following (in an Activity) :-
DatabaseHelper mDBHlp = new DatabaseHelper(this);
mDBHlp.cppInsert("''mydata'' \" other data\"");
Cursor csr1 = mDBHlp.getUnfiltered();
while (csr1.moveToNext()) {
Log.d("CSR1DATA",csr1.getString(csr1.getColumnIndex(DatabaseHelper.COLUMN1)));
}
csr1.close();
Cursor csr2 = mDBHlp.getFiltered();
while (csr2.moveToNext()) {
Log.d("CSR2DATA",csr2.getString(csr2.getColumnIndex(DatabaseHelper.COLUMN1)));
}
Results in :-
09-05 04:39:14.003 3471-3471/so52115977.so52115977 D/CSR1DATA: ''mydata'' " other data"
09-05 04:39:14.003 3471-3471/so52115977.so52115977 D/CSR2DATA: mydata other data
i.e. the second line is filtered accordingly.

How to display data from a database in a table?

I'm new to Android Studio and can't seem to find what I'm asking for.
I want to have a database that stores the data of a few people, e.g.
Steve Hardy, 16 Somewhere Land, Colorado, U.S.A.
I would like this to have headings (Name, Address, City, Country).
I'm just struggling with how to format a table like this and how I would link a database to this.
In android, mostly use sqlite databases. I can give you 3 simple functions I use to create database and table, insert data to table, & to read database values. If there is any unclear thing or you want any clarification, ask. I can help you.
public class MainActivity extends AppCompatActivity {
//Assign below 3 variables as global variables where class start.
SQLiteDatabase db; //Assign as a global variable
String DBName = "MyDB"; //Assign as a global variable
String TableName = "PeopleData"; //Assign as a global variable
//Call 3 function inside oncreate method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDB_Table(); //calling 3 functions.
InsertDataToDB();
ReadDBData();
}
public void createDB_Table(){ //This function use to create database, table & columns.
db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS " + TableName + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Address TEXT, City TEXT, Country TEXT);");
db.close();
}
public void InsertDataToDB(){ //This function use to inset values to database.
db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
ContentValues cv = new ContentValues();
cv.put("Name","Steve Hardy");
cv.put("Address","16 Somewhere Land");
cv.put("City","Colorado");
cv.put("Country","USA");
db.insert(TableName, null, cv);
db.close();
}
public void ReadDBData() { //This function use to read data from database.
db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
Cursor cursor = db.rawQuery("SELECT * FROM " + TableName, null);
if (cursor.getCount() > 0) { //check cursor is not empty.
cursor.moveToFirst();
String DName = cursor.getString(cursor.getColumnIndex("Name"));
String DAddress = cursor.getString(cursor.getColumnIndex("Address"));
String DCity = cursor.getString(cursor.getColumnIndex("City"));
String DCountry = cursor.getString(cursor.getColumnIndex("Country"));
//Got the values from database. Then you can set those values to text view or something you use.
}
cursor.close();
db.close();
}
}

Delete all tables from sqlite database

I have done a lot of research and was unable to find a suitable method to delete all the tables in an SQLite database. Finally, I did a code to get all table names from the database and I tried to delete the tables using the retrieved table names one by one. It didn't work as well.
Please suggest me a method to delete all tables from the database.
This is the code that I used:
public void deleteall(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
do
{
db.delete(c.getString(0),null,null);
}while (c.moveToNext());
}
function deleteall() is called on button click whos code is given as below:
public void ButtonClick(View view)
{
String Button_text;
Button_text = ((Button) view).getText().toString();
if(Button_text.equals("Delete Database"))
{
DatabaseHelper a = new DatabaseHelper(this);
a.deleteall();
Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
}}
Use DROP TABLE:
// query to obtain the names of all tables in your database
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();
// iterate over the result set, adding every table name to a list
while (c.moveToNext()) {
tables.add(c.getString(0));
}
// call DROP TABLE on every table name
for (String table : tables) {
String dropQuery = "DROP TABLE IF EXISTS " + table;
db.execSQL(dropQuery);
}
Tim Biegeleisen's answer almost worked for me, but because I used AUTOINCREMENT primary keys in my tables, there was a table called sqlite_sequence. SQLite would crash when the routine tried to drop that table. I couldn't catch the exception either. Looking at https://www.sqlite.org/fileformat.html#internal_schema_objects, I learned that there could be several of these internal schema tables that I shouldn't drop. The documentation says that any of these tables have names beginning with sqlite_ so I wrote this method
private void dropAllUserTables(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
//noinspection TryFinallyCanBeTryWithResources not available with API < 19
try {
List<String> tables = new ArrayList<>(cursor.getCount());
while (cursor.moveToNext()) {
tables.add(cursor.getString(0));
}
for (String table : tables) {
if (table.startsWith("sqlite_")) {
continue;
}
db.execSQL("DROP TABLE IF EXISTS " + table);
Log.v(LOG_TAG, "Dropped table " + table);
}
} finally {
cursor.close();
}
}
delete database instead of deleting tables and then create new with same name if you need. use following code
context.deleteDatabase(DATABASE_NAME);
or
context.deleteDatabase(path);
For me, the working solution is:
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type IS 'table'" +
" AND name NOT IN ('sqlite_master', 'sqlite_sequence')",
null
);
if(c.moveToFirst()){
do{
db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
}while(c.moveToNext());
}

Retrieving Data SQLite Database Issue

I create a database containing 4 String columns in a separate class called CalDatabaseHelper:
public void onCreate(SQLiteDatabase db) {
updateDatabase(db,0,DATABASE_VERSION);
}
private static void updateDatabase(SQLiteDatabase db, int olderversion, int newerVersion){
if (olderversion < 1){
db.execSQL("CREATE TABLE CAL (_id TEXT PRIMARY KEY,"
+ "ACTIVITY1 TEXT, "
+ "ACTIVITY2 TEXT"
+ "ACTIVITY3 TEXT);");
}
}
private static void insertIntoDatabase(SQLiteDatabase db, String primaryKey, String activityOne, String activityTwo, String activityThree){
ContentValues values = new ContentValues();
values.put("_id",primaryKey);
values.put("ACTIVITY1",activityOne);
values.put("ACTIVITY2",activityTwo);
values.put("ACTIVITY3",activityThree);
db.insert("CAL",null,values);
}
I add data in an Activity called Appointments. For now, I just add to the _id (a String variable) and ACTIVITY1 (a String variable that comes from user input into and EditText) columns:
SQLiteOpenHelper sqLiteOpenHelper = new CalDatabaseHelper(Appointments.this);
SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
values.put("_id",primaryKey);
values.put("ACTIVITY1", activityOne);
db.insert("CAL", null, values);
db.close();
I attempt to retrieve this data in an Adapter Class. Once a widget is clicked, a database is opened, a Cursor finds the two columns(_id, ACTIVITY1) and the data is retrieved. This class contains the primaryKey data that I use to search the database:
SQLiteOpenHelper sqLiteOpenHelper = new CalDatabaseHelper(context);
db = sqLiteOpenHelper.getReadableDatabase();
cursor = db.query("CAL",
new String[]{"_id","ACTIVITY1"},
"_id = ?",
new String[]{month_day_year},
null, null, null);
if (cursor.moveToFirst()){
String actOne = cursor.getString(0);
activityOne.setText(actOne);
}else{
Toast.makeText(context, "NOTHING FOUND DURING OPEN", Toast.LENGTH_LONG).show();
}
cursor.close();
db.close();
Up until this point, everything works fine. I am able to retrieve the data from the first column (_id) by using cursor.getString(0).
When I go to retrieve the data from the 2nd column (ACTIVITY1), I keep getting an empty String. For example, cursor.getString(1) returns "". This should be the data that my user inputted in my Appointments Activity. The data is clearly placed in to ContentValues within that class and then put in to the database. Any idea why nothing is coming up there? Is it because I am using db.insert() instead of the method I created in my databaseHelper class called insertIntoDatabase()? How come the primary key is inserted then anyway? Thank you

how to set the delete method in sqlite database correctly?

I have a database called "Users" and a table in that database called "contact". i want to delete a selected contact when I click a button. I want to know how to set the parameters correctly to the delete method. if somebody can gimme an answer with a little example i will be delighted .
my code goes like this
private void deleteContact(String name) {
SQLiteDatabase database=openOrCreateDatabase("Users",MODE_PRIVATE,null);
int res=database.delete("contact", "name =", name);
///
}
I call this method when I click that Button. my query is,
"delete from contact where name ='"+name+"';
If your datebase table name is Contact and name is unique identifier and name of column you are inserting names is COLUMN_NAME then
//Delete single item from Db
public void deleteContact(String name){
SQLiteDatabase db = this.getWritableDatabase();
db.delete("Contact", COLUMN_NAME + " = ?", new String[]{name});
db.close();
}
private void deleteContact(String name) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("contact","name=?" , new String[]{name});
db.close();
}

Categories

Resources