If we already have a database file in .sql format, how can we load this in our android app & use its data?
I also had this same problem and I did what jaydeep said. But I m not able to proceed..Please help me. I added 1 method in this to retrieve 1 record which is as follows:
public Cursor getTitle(String g,String k) throws SQLException {
Cursor c = myDataBase.rawQuery(
"select * from titles where food LIKE '%"+g+"%' and area LIKE '%"+k+"%' ",
null);
if (c != null) {
c.moveToFirst();
}
return c;
}
where titles is id name of table in database n food area n rest are fields. and in main file i did as follows:
{
Datahelper myDbHelper = new Datahelper(this);
final String tem="Chinese";
final String tem2="Bur Dubai";
final ListView list = (ListView)findViewById(R.id.list);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Cursor c = myDbHelper.getTitle(tem,tem2);
if (c.moveToFirst()) DisplayTitle(c);
else Toast.makeText(this, "No title found",
Toast.LENGTH_LONG).show();
}
public void DisplayTitle(Cursor c) {
final TextView ter=(TextView)findViewById(R.id.ter);
c.moveToPosition(0);
while (c.isAfterLast() == false) {
ter.append(c.getString(3)+"\n");
c.moveToNext();
}
c.close();
}
Please help me.
ListView code:
if (c.moveToFirst())
{
final String [] restarr=c.getColumnNames();
String[] fields = new String[] {db.KEY_REST};
list.setAdapter(new ArrayAdapter<String>(this, R.layout.main, restarr));
SimpleCursorAdapter rest = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,fields, new int[] {android.R.id.text1});
list.setAdapter(rest);
}
You need SQLite version of the database. I bet your current database you want to ship to the application, has schema written with pure SQL syntax which quite different from SQLite.
If my assumption is true, then you need to extract the schema and convert it to SQLite. This takes some minor changes in the syntax but logic stays the same.
Here is nice tutorial how you can ship your external local database in your android application:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
Mind the version and extension of the database file.
Related
I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.
Is there a good method or query to check if the UserId == ThreadId?
My current code:
public void deleteThread() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_THREAD, null, null);
db.close();
Log.d(TAG, "Deleted all Thread info from sqlite");
}
You need to pass correct value to the well-documented delete method to narrow down the scope of deletion to a subset of all entries in the DB table.
public void deleteThreadById(String threadId) {
SQLiteDatabase db = this.getWritableDatabase();
String whereClause = "threadId = " + threadId;
db.delete(TABLE_THREAD, whereClause, null);
db.close();
}
Deleting all threads of a given user via their userId would be similar but probably doesn't make sense in a forum software.
This is how SQL works in general and it's a bit scary you started development without familiarising yourself with the very basics.
Something like this;
public void deleteThread(String threadName) {
SQLiteDatabase db = this.getWritableDatabase();
try {
db.delete(MYDATABASE_TABLE, "name = ?", new String[]{threadName});
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
Something long these lines, querying database to find the specific row that has column which matches the parameter.
For example to delete a row which the name column is "Hello World";
deleteThread("Hello World");
I have been struggling for hours trying to use an array inside a while loop. The problem is that im very new to android development so i have no idea how to do this. I have seen similar questions but most/all of them does not suite for my scenario. The code below does work but im calling a new instance of articlesData for each row in the while statement, this causes it to just return the value of the last row.. Is there any way to use an array like ArticlesData[] and get all my data in it? Please help :) Here is my code:
public ArticlesData[] getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
articlesData = new ArticlesData[] {
new ArticlesData(title, Integer.toString(id), url)
};
}
return articlesData;
}
You most probably want to use a Collection such as List:
public List<ArticlesData> getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
List<ArticlesData> list = new ArrayList<ArticlesData>();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
list.add(new ArticlesData(title, Integer.toString(id), url));
}
return list;
}
You should not try to use a raw array here because it has a fixed size. You could use it if you limited the number of rows in the query so you'd know exactly how much elements you need, but even then it would still be much easier to just use a Collection elsewhere in the code.
As you seem new to Android development and Java I suggest you first get acquainted with the basic data structures such as Maps, Lists, and Sets, and then later you might want to use an ORM to save you the pain of writing boilerplate code for interacting with a database.
public void DatabaseConn() {
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Driver", null);
startManagingCursor(c);
//create an array to specify which fields we want to display
String[] from = new String[]{"Driver_Name"};
//create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
//create simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//get reference to our spinner
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
s.setAdapter(adapter);
db.close();
}
Is that possible Bind Spinner Without _id Column? any idea?
Edited : Except SimpleCursorAdapter, any others adapter able to do this? I mean without _id column
From the android documentation for CursorAdapter which is the superclass of the SimpleCursorAdapter you are using:
The Cursor must include a column named "_id" or this class will not work.
So, no.
Edit:
Actually, there is a way to get around this issue. If you read carefully, it says that the Cursor must have a column named _id, which we can get by changing your query string to:
"SELECT ROWID AS _id, someColumn, anotherColumn FROM Tbl_Driver"
You will have to manually type out all of the columns you want though since doing ROWID AS _id will not work at the same time as using the wildcard *.
I was following this tutroial about using your own SQLite database. I did these steps as described in the tutorial:
Preparing my database
Copying the same EXACT DataBaseHelper class to my project package. You can see the class code there
Then, I just added one method to the DataBaseHelper class which is fetchData. It is simply fetching a whole table with the given name:
public Cursor fetchData(String table) {
String[] selectionArgs = new String[] {"*"};
return myDataBase.query(table, null, null, selectionArgs, null, null, null);
}
After that, in one of my activity classes I did this:
DataBaseHelper myDbHelper;
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
TextView txt = (TextView) findViewById(R.id.txt);
try {
//I will use my method to fetch a table named: myTable
Cursor c = myDbHelper.fetchData("myTable");
if((Object)c.getCount() != null)
txt.setText(c.getCount());
else
txt.setText("null");
} catch(Exception e) {
txt.setText("error");
}
However, I keep getting 'error' in the TextView. Is there a problem in my way?
My problem is nothing related to SQLite. It was silly mistake :-\
The error is in the second line here:
if((Object)c.getCount() != null)
txt.setText(c.getCount());
It must be like this:
txt.setText(""+c.getCount());
the setText() method accepts a ChaSequence and the getCount() method returns Integer which are not in compatible type. you can work around that tha easy way, by adding empty string :)
Thanks Guys.
public Cursor fetchData(String table) {
return myDataBase.query(table, null, null, null, null, null, null);
}
Seems you got wrong idea about the selectionArgs parameter. In documentation, it says:
You may include ?s in selection, which
will be replaced by the values from
selectionArgs, in order that they
appear in the selection. The values
will be bound as Strings.
Your trying to cast an int as an Object, then comparing the cast value to null. I would say that you code is likely to break right there.
So right now I'm using this solution in my app Ship an application with a database
In my main activity, I just want to test to make sure that the database is working, so all I'm doing it a simply query to get some names, all I did was add 3 lines(commented where I added them):
DatabaseHelper myDbHelper;
SQLiteDatabase myDb = null;
myDbHelper = new DatabaseHelper(this);
/*
* Database must be initialized before it can be used. This will ensure
* that the database exists and is the current version.
*/
myDbHelper.initializeDataBase();
Cursor c;
String s = null;
try {
// A reference to the database can be obtained after initialization.
myDb = myDbHelper.getWritableDatabase();
//the next 3 lines are all I added
c = myDb.rawQuery("select name from breads", null);
s = c.getString(1);
c.close();
/*
* Place code to use database here.
*/
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
myDbHelper.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
myDb.close();
}
}
However, s just remains empty. If I do the exact same query select name from breads in the console, I will get data. Does anyone have any ideas?
myDb = myDbHelper.getWritableDatabase();
//the next 3 lines are all I added
c = myDb.rawQuery("select name from breads", null);
c.moveToFirst(); // ADD THIS
s = c.getString(1);
c.close();