android sqlite: How to select differet table data in different database - java

I have imported two databases (one is omstar0 which have a table omstar, another is omstar1 which have a table omstarline) which were stored in asset file in sdcard of android. android sqlite: How to select differet table data in different database? I mean I want to select all the data in two databases. The following is my code:
public class DBManager {
private Context context;
public final String DB_PATH2 =
android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/tianke";
private final String DB_NAME = "omstar0.db";
private SQLiteDatabase database;
private final int BUFFER_SIZE = 1024;
DBManager(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
for(int i = 0; i<2; i++) {
File dbFile = new File(DB_PATH2+"/omstar"+String.valueOf(i)+".db");
if(!dbFile.exists()){
//InputStream is = this.context.getResources().openRawResource(R.raw.);
try {
//创建目录
File pmsPaht = new File(DB_PATH2);
Log.i("pmsPaht", "pmsPaht: "+pmsPaht.getPath());
pmsPaht.mkdirs();
AssetManager am = this.context.getAssets();
InputStream is = am.open("/omstar"+String.valueOf(i)+".db");
FileOutputStream fos = new FileOutputStream(dbFile);
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.flush();
fos.close();
is.close();
am.close();
}catch (IOException e) {
e.printStackTrace();
}
}
database = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
}
System.out.println("2: sucesseful");
return database;
}
//http://jalhaskazakhlike.lofter.com/post/3f320a_15df9b3
//http://www.cnblogs.com/xiaowenji/archive/2011/01/03/1925014.html
public void closeDatabase() {
if (database!=null){
this.database.close();
}
}
}
public class SDDatabaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button create = (Button) findViewById(R.id.button1);
Button query = (Button) findViewById(R.id.button2);
create.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createDB();
}
});
query.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
queryDB();
}
});
}
public void createDB()
{
DBManager dbm = new DBManager(this);
dbm.openDatabase();
dbm.closeDatabase();
}
public void queryDB()
{
String sql = "select * from omstar";
DBManager dbm = new DBManager(this);
SQLiteDatabase db = dbm.openDatabase();
Cursor cur = db.rawQuery(sql, null);
while (cur.moveToNext())
{
//String id = cur.getColumnName(1);
//float la = cur.ge;
//float id = cur.getColumnName(1);
int id = cur.getInt(0);
String name = cur.getString(1);
String email = cur.getString(2);
Log.i("latitude", "id:"+id);
System.out.println("id:"+id);
System.out.println("name:"+name);
System.out.println("Email:"+email);
}
cur.close();
db.close();
}
}

SELECT Columnname FROM Database1.Table ,Database2.Table
WHERE
Database1.Table.Column(Primary Key) = Database2.Table.Column(Primary Key);

Related

How to get data from a sqllite database and store it in ListView

I have a data base I need to read data from it and view it in a list view it contain some tables from them a table named "main_categories" which has one field called "category_name" which is the primary key
this is the DataAdapter:
public DataAdapter(Context context) {
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public DataAdapter createDatabase() throws SQLException {
try {
mDbHelper.createDataBase();
} catch (IOException mIOException) {
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public DataAdapter open() throws SQLException {
try {
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
} catch (SQLException mSQLException) {
Log.e(TAG, "open >>" + mSQLException.toString());
throw mSQLException;
}
return this;
}
public void close() {
mDbHelper.close();
}
public Cursor getTestData() {
try {
String sql = "SELECT * FROM myTable";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur != null) {
mCur.moveToNext();
}
return mCur;
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>" + mSQLException.toString());
throw mSQLException;
}
}
}
and this is the DataBaseHelper:
public class DataBaseHelper extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private static String DB_PATH = "";
private static String DB_NAME ="my_knowledge";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context)
{
super(context, DB_NAME, null, 1);// 1? Its database Version
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
this.mContext = context;
}
public void createDataBase() throws IOException
{
//If the database does not exist, copy it from the assets.
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
this.getReadableDatabase();
this.close();
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
//Open the database, so we can query it
public boolean openDataBase() throws SQLException
{
String mPath = DB_PATH + DB_NAME;
//Log.v("mPath", mPath);
mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
#Override
public synchronized void close()
{
if(mDataBase != null)
mDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
and this is the main activity for now:
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabase;
private static String DB_NAME ="my_knowledge"; // Database name
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = findViewById(R.id.main_list);
DataAdapter mDbHelper = new DataAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
Cursor testdata = mDbHelper.getTestData();
mDbHelper.close();
}
}
I want to know a way to store the data in the tables of the array (for example "main_categories") and view them with the list view
Depending on your table column type
List<String> temp;
testdata.moveToFirst();
do {
temp.add(testdata.getString(0));
} while (testdata.moveToNext());
Your cursor testdata has the first row in testdata.moveToFirst(); and each column is associated with column index i.e. 0, 1 etc.
testdata.moveToNext(); will have successive rows.
A couple of things:
First of, I would consider adding a query method to your DataBaseHelper class instead of using a rawQuery, something like:
Cursor query(String table, String[] projection, String where, String orderBy) {
return getReadableDatabase().query(table, projection, where, null, null, null, orderBy);
}
You can call the query method inside mDbHelper.getTestData() and use the Cursor object to populate your list.
Take a look at using a Cursor Loader?
to do get the data out of the cursor and into your adapter.

no such table SQLite error could not compile

i have three classes where the flow is..
entering the entry to be searched: (from MainActivity)
try {
String input = etSearch.getText().toString();
Intent i = new Intent(this, SearchViewList.class);
i.putExtra("input", input);
Log.i("input", input + "");
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Row Empty or ID not found!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
break;
}
then the class SearchViewList would display the list by the searched value from the intent
Intent i = getIntent();
input = i.getStringExtra("input");
String l = input;
datasource = new DatabaseHelper(this);
datasource.openDataBase();
List<Definition> values = datasource.getSearchedDefinition(l);
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Definition> adapter = new ArrayAdapter<Definition>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
String str = ((TextView) view).getText().toString();
Log.i(str, str + "");
Intent i = new Intent(getApplicationContext(),
SearchedView.class);
i.putExtra("value", str);
startActivity(i);
}
});
then after clicking the searched entry from the list then the error commence
Intent i = getIntent();
l = i.getStringExtra("value");
TextView entry = (TextView) findViewById(R.id.tvEntry);
datasource = new DatabaseHelper(this);
datasource.openDataBase();
String dataEntry = datasource.getEntry(l);
datasource.close();
entry.setText(dataEntry);
}
here is my getEntry() method from the DatabaseHelper class
public String getEntry(String l) throws SQLException {
Cursor c = myDataBase.rawQuery(
"SELECT entry FROM defintionstbl where entry = '"
+ l + "'", null);
if (c != null) {
c.moveToFirst();
if (c.getCount() <= 0) {
return null;
}
String entry = c.getString(0);
return entry;
}
return null;
}
this next method is also from the DatabaseHelper class
public List<Definition> getSearchedDefinition(String l) throws SQLException {
List<Definition> entries = new ArrayList<Definition>();
Cursor cursor = myDataBase.rawQuery(
"SELECT entry FROM definitionstbl where entry like '" + l + "%'", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Definition entry = cursorToDefinition(cursor);
entries.add(entry);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return entries;
}
private Definition cursorToDefinition(Cursor cursor) {
Definition entry = new Definition();
entry.setId(cursor.getLong(0));
entry.setEntry(cursor.getString(0));
return entry;
}
this method compile just fine but the i am getting a "no such table definitionstbl" error from the method getEntry().
additional note:
database = dictionary.sqlite
table = definitionstbl
column1 = _id
column2 = entry
column3 = definitions
here is the code for the copying of the database from an external source:
public class DatabaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.gtxradeon.newversioncomputerdictionary/databases/";
private static String DB_NAME = "dictionary.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
create table from MainActivity
try {
myDbHelper.createDataBase();
myDbHelperTrivia.createDataBase();
Log.i("CREATING", "DATABASE CREATED");
} catch (Exception e) {
Log.i("CREATE", "Exception Caught! ", e);
}
try {
myDbHelper.openDataBase();
Log.i("OPENING", "DATABASE OPENED");
} catch (SQLException e) {
Log.i("OPEN", "Exception Caught! ", e);
}
thanks for helping guys but i just changed the getEntry method to this.. rawQuery gave alot of error but this new method is good to go..
public String getEntry(String l) throws SQLException {
String[] columns = new String[] { "_id",
"entry", "definition" };
Cursor c = myDataBase.query("definitionstbl", columns,
"entry" + "='" + l + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
if (c.getCount() <= 0) {
return null;
}
String entry = c.getString(1);
return entry;
}
return null;
}

get others column value on onItemSelected in Android

My Tbl_Driver have 3 columns _id,Driver_Code,Driver_Name
How do i able to get the Driver_Name when the Spinner OnItemSelected, because The Spinner will only show Driver_Code
public void DriverDatabaseConn(){
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);
//=====Add Additional=====
MatrixCursor extras = new MatrixCursor(new String[] { "_id", "Driver_Code" , "Driver_Name"});
extras.addRow(new String[] { "-1", "< Select Driver Code >","< Select Driver >" });
//extras.addRow(new String[] { "-2", "Empty Template","BB" });
Cursor[] cursors = { extras, c };
c = new MergeCursor(cursors);
//===========================
startManagingCursor(c);
//create an array to specify which fields we want to display
String[] from = new String[]{"Driver_Code"};
//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);
s.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
TextView textView = (TextView)s.getSelectedView();
String result = textView.getText().toString();
Log.d(null,"Spinner1: position=" + result + " id=" + id);
global.Driver_ID = id;
global.Driver_Code = result;
// at here how i can get the Driver_Name column's value at here?
}
public void onNothingSelected(AdapterView<?> parent) {
Log.d(null,"Spinner1: unselected");
}
});
//db.close();
//myDbHelper.close(); //cannot close, otherwise after logout the spinner will blank
}
DataBaseHelper.java
package com.example.abc2;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.example.abc2/databases/";
private static String DB_NAME = "DB_BusData";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
I have rewrite your DatabaseHelpe and a Test Activity:
public class DataBaseHelper {
private static final String DB_NAME = "DB_BusData";
public static final String TABLE_NAME = "Tbl_Driver";
private Context context;
private String path;
private SQLiteDatabase database;
private boolean isInitializing = false;
public DataBaseHelper(Context context) {
this.context = context;
this.path = context.getDatabasePath(DB_NAME).getAbsolutePath();
if (TextUtils.isEmpty(this.path)) {
throw new IllegalArgumentException("database can't be null");
}
}
public SQLiteDatabase getReadableDatabase() {
synchronized (this) {
checkAndCopyDatabase();
return getDatabaseLocked(false);
}
}
/**
* Attention:just support readable database until now
*
* #return
*/
public SQLiteDatabase getWriteableDatabase() {
synchronized (this) {
checkAndCopyDatabase();
return getDatabaseLocked(true);
}
}
private void checkAndCopyDatabase() {
File file = new File(this.path);
if (file.exists() && file.length() > 0) {
Log.d("TAG", "db already exist");
} else {
try {
InputStream is = context.getAssets().open(DB_NAME);
copyStreamToFile(is, new File(this.path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static final void copyStreamToFile(InputStream inputStream, File file) {
ensureDir(file);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int read = 0;
while ((read = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
quietClose(inputStream);
quietClose(fos);
}
}
private static final void ensureDir(File file) {
if (file != null && (file = file.getParentFile()) != null && !file.exists()) {
file.mkdirs();
}
}
private static final void quietClose(final Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (final IOException e) {
}
}
}
private SQLiteDatabase getDatabaseLocked(boolean writeable) {
if (this.database != null) {
if (!this.database.isOpen()) {
database = null;
} else if (!writeable || !database.isReadOnly()) {
return database;
}
}
if (isInitializing) {
throw new IllegalArgumentException("getDatabase called recursively");
}
SQLiteDatabase db = this.database;
try {
isInitializing = true;
if (db != null && writeable && db.isReadOnly()) {
if (db.isOpen()) {
db.close();
}
db = null;
}
try {
db = SQLiteDatabase.openDatabase(this.path, null,
writeable ? SQLiteDatabase.OPEN_READWRITE : SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
this.database = db;
return db;
} finally {
isInitializing = false;
if (db != null && db != database) {
db.close();
}
}
}
public static class Driver implements BaseColumns {
long id;
String code;
String name;
static final String CODE_CLOMN_NAME = "Driver_Code";
static final String NAME_CLOMN_Name = "Driver_Name";
#Override
public String toString() {
return name;
}
}
public List<Driver> queryAllDriver() {
List<Driver> drivers = null;
SQLiteDatabase db = getReadableDatabase();
if (db != null) {
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
if(cursor != null && cursor.moveToFirst()) {
do {
final long id = cursor.getLong(cursor.getColumnIndex(Driver._ID));
final String code = cursor.getString(cursor.getColumnIndex(Driver.CODE_CLOMN_NAME));
final String name = cursor.getString(cursor.getColumnIndex(Driver.NAME_CLOMN_Name));
Driver driver = new Driver();
driver.id = id;
driver.code = code;
driver.name = name;
if(drivers == null)
drivers = new ArrayList<DataBaseHelper.Driver>();
drivers.add(driver);
} while(cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if(cursor != null)
cursor.close();
}
db.close();
}
return drivers;
}
}
The DB open and operation code is above, then I write a Test Activity:
public class MainActivity extends Activity implements OnItemSelectedListener {
private List<Driver> drivers;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
new DBTask().execute();
}
class DBTask extends AsyncTask<Void, Void, List<Driver>> {
#Override
protected List<Driver> doInBackground(Void... params) {
DataBaseHelper dbHelper = new DataBaseHelper(MainActivity.this);
return dbHelper.queryAllDriver();
}
#Override
protected void onPostExecute(List<Driver> result) {
bindSpinner(result);
}
}
private void bindSpinner(List<Driver> drivers) {
this.drivers = drivers != null ? drivers : new ArrayList<DataBaseHelper.Driver>(0);
ArrayAdapter<Driver> adapter = new ArrayAdapter<DataBaseHelper.Driver>(this,
android.R.layout.simple_spinner_item, this.drivers);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (this.spinner != null && position >= 0 && position < this.drivers.size()) {
Driver driver = drivers.get(position);
Toast.makeText(this, "selected: driver=" + driver.name + ", code=" + driver.code,
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(this, "nothing selected", Toast.LENGTH_SHORT).show();
}
}
The Test Activity is works fine for me, I use the database that I simulated. I think you can't store spinner item in database, how many item in spinner? 10? 100 ? 1000?
You can move query data outside DataBaseHelper.java like this:
private List<Driver> queryAllDriver() {
List<Driver> drivers = null;
DataBaseHelper helper = new DataBaseHelper(this);
SQLiteDatabase db = helper.getReadableDatabase();
if (db != null) {
Cursor cursor = null;
try {
cursor = db.query(DataBaseHelper.TABLE_NAME, null, null, null, null, null, null);
if(cursor != null && cursor.moveToFirst()) {
do {
final long id = cursor.getLong(cursor.getColumnIndex(Driver._ID));
final String code = cursor.getString(cursor.getColumnIndex(Driver.CODE_CLOMN_NAME));
final String name = cursor.getString(cursor.getColumnIndex(Driver.NAME_CLOMN_Name));
Driver driver = new Driver();
driver.id = id;
driver.code = code;
driver.name = name;
if(drivers == null)
drivers = new ArrayList<DataBaseHelper.Driver>();
drivers.add(driver);
} while(cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if(cursor != null)
cursor.close();
}
db.close();
}
return drivers;
}

Want to insert json data into the Sqlite Database

I want to store an json data to db,it has to display my apps has to display some previous data without internet time also.For that i want to create an db for json data to store.
This is the db part i created for json data.
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "ginfy.db";
private static final String DATABASE_TABLE_PROJ = "prayers";
private static final int DATABASE_VERSION = 2;
public static final String CATEGORY_COLUMN_ID = "id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "ProjectDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public GinfyDbAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
}
public GinfyDbAdapter GinfyDbAdapter(Context context){
mDbHelper = new DatabaseHelper(context);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key autoincrement, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer primary key autoincrement );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER PRIMARY KEY )" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_NAME);
onCreate(db);
}
}
}
this is mainactivity which is showing listview
public class MainActivity extends Activity implements FetchDataListener,OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final String TAG_CATEGORY = "post";
private static final String CATEGORY_COLUMN_ID = "id";
private static final String CATEGORY_COLUMN_TITLE = "title";
private static final String CATEGORY_COLUMN_CONTENT = "content";
private static final String CATEGORY_COLUMN_COUNT = "count";
private static final int Application = 0;
private ProgressDialog dialog;
ListView lv;
ListView lv1;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int pct;
private String stringVal;
private TextView value;
private int prayers;
private int prayerid;
EditText myFilter;
ApplicationAdapter adapter;
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
//JSONParser jParser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(id,title,content,count);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(CATEGORY_COLUMN_ID, id);
map.put(CATEGORY_COLUMN_TITLE, title);
map.put(CATEGORY_COLUMN_CONTENT, content);
map.put(CATEGORY_COLUMN_COUNT, count);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddPrayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data){
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
/*dataAdapter adapter = new SimpleCursorAdapter(this,
R.layout.activity_row,
new String[] { CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, new int[] {
R.id.text2, R.id.text1, R.id.count });*/
//lv.setListAdapter(adapter);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg){
if ( dialog != null )
dialog.dismiss();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
Before using db it shows in listview also,rite now i want to make db also,for that i wrote some code in mainactivity.
Fetchdatatask.java
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private OnClickListener onClickListener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
app.setTitle(json.getString("title"));
app.setCount(Integer.parseInt(json.getString("count")));
app.setId(Integer.parseInt(json.getString("id")));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
This fetchdatatask fetch from json and showing in listview,i want that without internet time it has to show in listview also for that i am creating db.
can you check my code is correct,actually it showing error in mainactivity line JSONArray aJson = jsonObject.getJSONFromUrl(url);
Create a class which act's as the intermediate between your Db class and the main activity to insert the data into the db and vice versa
public class Category {
String id;
String title;
String content;
String count;
public Category(String id, String title, String content, String count) {
super();
this.id = id;
this.title = title;
this.content = content;
this.count = count;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
In your main activity where you do the json parsing create an object of DB class and call one the save record method at there like i did below
DatabaseHelper mDbHelper;
public class ABC extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
mDbHelper= new DatabaseHelper (this);
new GetSyncDataAsyncTask().execute();
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog Dialog = new ProgressDialog(ABC.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Dialog.dismiss();
Intent intent = new Intent(ABC.this, XYZ.class);
startActivity(intent);
}
#Override
protected Boolean doInBackground(Void... params) {
getData();
return null;
}
}
public void getProdData() {
// getting JSON string from URL
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
At last in your db class insert the values like below
public void saveCategoryRecord(Category category) {
String query = "insert into"+ TABLE_NAME+ values( ?, ?, ?, ?, ?, ? )";
SQLiteStatement stmt = mDb.compileStatement(query);
stmt.bindString(1, category.getId());
stmt.bindString(2, category.getTitle());
stmt.bindString(3, category.getContent());
stmt.bindString(4, category.getCount());
stmt.execute();
}
I have tried to use the same things as you have used. This is the way i think now you got the concept to do that

Copying database works on emulator but not on device

This works on the emulator but not on my phone. At least it seems so because it does not find the table when I query it on the phone.
This my class that inherits from SQLiteOpenHelper
public class DBHelper extends SQLiteOpenHelper {
private final static String DB_NAME = "klb_db.sqlite";
private final static int DB_VERSION = 1;
private String dbPath;
private Context context;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
dbPath = "/" + Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/databases/";
}
public void initializeDatabase() {
try {
File file = new File(dbPath + DB_NAME);
if (!file.exists()) {
InputStream inputStream = context.getAssets().open(
"klb_db.sqlite");
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In dbadapter, open method:
public DBAdapter open() {
dbHelper.initializeDatabase();
db = dbHelper.getWritableDatabase();
return this;
}
In activity that uses it:
#Override
protected void onStart() {
super.onStart();
QuizDAO quizDAO = new QuizDAO(this);
quizDAO.open();
Cursor cursor = quizDAO.getQuestion(10);
Toast.makeText(this, cursor.getString(1), Toast.LENGTH_LONG).show();
}
try to increase you bytes
byte[] buffer = new byte[1024];
to
byte[] buffer = new byte[2048];
EDITED
#Override
protected void onStart() {
super.onStart();
QuizDAO quizDAO = new QuizDAO(this);
quizDAO.open();
Cursor cursor = quizDAO.getQuestion(10);
cursor.moveToFirst()
Toast.makeText(this, cursor.getString(1), Toast.LENGTH_LONG).show();
}

Categories