I need to display data from 4 different database tables in android. Previously for testing I used single table to display data. For that I have created three files.
1)DBAdapter.java
2)UserBO.java
3)Test.java
DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "mydb.sqlite";
private SQLiteDatabase myDataBase1;
private final Context myContext1;
private static DBAdapter mDBConnection;
private DBAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.myContext1 = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
}
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
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;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext1.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 {
String myPath = DB_PATH + DB_NAME;
myDataBase1 = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (myDataBase1 != null)
myDataBase1.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
return myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
return myDataBase1.rawQuery(query, selectionArgs);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
}
**UserBO.java**
public class UserBO {
int sid;
String sname;
public int getsid() {
return sid;
}
public void setsid(int sid) {
this.sid = sid;
}
public String getsname() {
return sname;
}
public void setsname(String sname) {
this.sname= sname;
}
}
Test.java
public class Select extends Activity {
private Header header;
private ListView lvUsers;
private ArrayList<UserBO> mListUsers;
private SharedPreferences mPreferences1;
private SharedPreferences mPreferences2;
String myString1,query;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("before k select "+k);
setContentView(R.layout.select);
header = (Header) findViewById(R.id.layoutHeader);
mListUsers = getUsers();
lvUsers = (ListView) findViewById(R.id.lv_user);
lvUsers.setAdapter(new ListAdapter(this, R.id.lv_user, mListUsers));
}
public ArrayList<UserBO> getUsers(){
DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
mPreferences1 = getSharedPreferences("CurrentUser1", 0);
myString1 = mPreferences1.getString("student id",sid);
dbAdapter.openDataBase();
**query="SELECT tabel1.*, tabel2.* FROM tabel1, tabel2 WHERE tabel1.PK=tabel2.FK;";**
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
AppConstants.alConductedQuestions.add(user);
System.out.println("mListUsers");
System.out.println(user);
try {
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
}
catch (Exception e) {
Log.i("***" + Test.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
// ***ListAdapter***
private class ListAdapter extends ArrayAdapter<UserBO> { // --CloneChangeRequired
private ArrayList<UserBO> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<UserBO> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
//System.out.println(list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null);
// --CloneChangeRequired(list_item)
}
final UserBO listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting list_item views
( (TextView) view.findViewById(R.id.casedescription) ).setText( listItem.getsid()+"");
( (TextView) view.findViewById(R.id.tv_question) ).setText( listItem.getsname()+"");
ArrayList<UserBO> mList1;
}
}
catch(Exception e){
String err = (e.getMessage()==null)?"hii":e.getMessage();
Log.e("sdcard-err2:",err);
}
return view;
}
}
}
In test.java I am writing the query. In UserBO I am writing the setter and getter methods. In DBAdapter file I am mentioning the database name. So here my question is I have 4 tables in my database. So I need to display data using those tables. Shall I write the setter and getter methods of the column names of all the tables in one single UserBO file?
Also I am getting the values of each column of single table by giving
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
*How do I get the column names of all the tables?* I mean shall I need to get all the columns of all the tables in Test.java file?
Please help me regarding this....I am it confused with this different tables.....
Thanks in Advance
you have one database & three tables or all three tables are in different databsaes ?
Related
How can I solve this problem would in android ?
07-07 14:44:58.122: E/CursorWindow(12281): Could not allocate CursorWindow '/storage/emulated/0/Android/data/com.example.mytestlistview/Mafatih/Mafatih.db' of size 2097152 due to error -12.
I create a SearchBox on a DB that it is 10MB .That show the results of search on ListView but get me this error.
My StructNote.java :
public class StructNote {
public String Title;
public String Comment;
public StructNote(String Title,String Comment)
{
super();
this.Title = Title;
this.Comment = Comment;
}
public String getTitle()
{
return Title;
}
public String getComment()
{
return Comment;
}
}
My MainActivity.java :
public class MainActivity extends ActionBarActivity {
public static final String DIR_SDCARD = Environment
.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Android/data/";
public ArrayList<StructNote> notes = new ArrayList<StructNote>();
public ArrayAdapter adapter;
public String Titel_Drawer;
public Integer titleID;
public Cursor cursorid;
public ArrayList<String> array;
public static String PACKAGE_NAME;
EditText editText;
DB db = new DB(MainActivity.this);
public Cursor cursor;
public SQLiteDatabase sql;
public ListView lstContent;
int selectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PACKAGE_NAME = getApplicationContext().getPackageName();
File file = new File(DIR_DATABASE + PACKAGE_NAME + "/Mafatih");
file.mkdirs();
db.GetPackageName(PACKAGE_NAME);
db.CreateFile();
try {
db.CreateandOpenDataBase();
} catch (IOException e) {
e.printStackTrace();
}
sql = db.openDataBase();
final ListView lstContent = (ListView) findViewById(R.id.lstContent);
adapter = new AdapterNote(notes);
lstContent.setAdapter(adapter);
editText = (EditText) findViewById(R.id.search);
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (editText.getText().length() < 2) {
Toast.makeText(MainActivity.this, "Please enter more text !", Toast.LENGTH_SHORT).show();
return true;
}
else
{
populateListView(editText.getText());
return true;
}
}
else if(keyCode == KeyEvent.KEYCODE_DEL) {
adapter.clear();
return false;
}
return false;
}
});
final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.Language);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
selectedId = radioGroup.getCheckedRadioButtonId();
Log.i("xxx", String.valueOf(selectedId));
}
});
}
public void populateListView(Editable editable) {
if(selectedId == 2131034177)
{
try {
cursor = sql.rawQuery(
"SELECT * FROM WebSite_MetaDataDBBack WHERE Comment LIKE '"
+"%"+ editable + "%'", null);
array = new ArrayList<String>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
StructNote note = new StructNote(Titel_Drawer, Titel_Drawer);
note.Comment = cursor.getString(cursor
.getColumnIndex("Comment"));
titleID = cursor.getInt(cursor
.getColumnIndex("CategoryID"));
cursorid = sql.rawQuery(
"SELECT Title FROM WebSite_CategoryBack WHERE CategoryID ="
+ titleID, null);
if (cursorid != null) {
do {
cursorid.moveToFirst();
note.Title = cursorid.getString(cursorid
.getColumnIndex("Title"));
} while (cursorid.moveToNext());
}
notes.add(note);
} while (cursor.moveToNext());
}
adapter.notifyDataSetChanged();
cursor.close();
}
} catch (Exception e) {
Log.i("xxx", "You have an error");
}
}
else if(selectedId == 2131034176)
{
try {
cursor = sql.rawQuery(
"SELECT Tafsir,CategoryID FROM WebSite_MetaDataDBBack WHERE Tafsir LIKE '"
+"%"+ editable + "%'", null);
array = new ArrayList<String>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
StructNote note = new StructNote(Titel_Drawer, Titel_Drawer);
note.Comment = cursor.getString(cursor
.getColumnIndex("Tafsir"));
titleID = cursor.getInt(cursor
.getColumnIndex("CategoryID"));
cursorid = sql.rawQuery(
"SELECT Title FROM WebSite_CategoryBack WHERE CategoryID ="
+ titleID, null);
if (cursorid != null) {
do {
cursorid.moveToFirst();
note.Title = cursorid.getString(cursorid
.getColumnIndex("Title"));
} while (cursorid.moveToNext());
}
notes.add(note);
} while (cursor.moveToNext());
}
adapter.notifyDataSetChanged();
cursor.close();
}
} catch (Exception e) {
Log.i("xxx", "You have an error");
}
}
}
}
My AdapterNote.java :
public class AdapterNote extends ArrayAdapter<StructNote> {
public AdapterNote(ArrayList<StructNote> array) {
super(G.context, R.layout.dapter_notes, array);
}
public static class ViewHolder {
public TextView txtTitle;
public TextView txtDescription;
public ViewHolder(View view) {
txtTitle = (TextView) view.findViewById(R.id.txtTitle);
txtDescription = (TextView) view.findViewById(R.id.txtDescription);
}
public void fill(ArrayAdapter<StructNote> adapter, StructNote item,
int position) {
txtTitle.setText(item.Title);
txtDescription.setText(item.Comment);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
StructNote item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.dapter_notes, parent,
false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
}
My G.java :
public class G extends Application{
public static Context context;
public static LayoutInflater inflater;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
And this is my Db.java for DB :
public class DB extends SQLiteOpenHelper{
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD +"/Android/data/";
private static String DB_NAME = "Mafatih.db";
private final Context myContext;
public static String PACKAGE_NAME;
public boolean flag = false;
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 = DIR_DATABASE +PACKAGE_NAME+"/Mafatih/"+ 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;
try{
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
}
catch (IOException e) {
Log.e("Copy", e.toString());
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
checkDB = SQLiteDatabase.openDatabase(DIR_DATABASE +PACKAGE_NAME+ "/Mafatih/" + DB_NAME, null, 0);
}catch(SQLiteException e){
Log.e("asdf", "checkDataBase-->"+e.toString());
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
#Override
public synchronized SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}
public DB(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void CreateandOpenDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
}
else
{
try {
copyDataBase();
}
catch (IOException e) {
throw new Error("Error copying database --> "+e.toString());
}
}
}
public SQLiteDatabase openDataBase() throws SQLException{
return SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE +PACKAGE_NAME+ "/Mafatih/" +DB_NAME, null);
}
public boolean CreateFile(){
if(flag == false)
{
File file= new File(DIR_DATABASE);
file.mkdirs();
return true;
}
else
{
return true;
}
}
public void GetPackageName(String res){
PACKAGE_NAME = res;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Problem : Could not allocate CursorWindow '.....' of size 2097152 due to error -12.
Reason: Most of the times this issue arises due to non-closure of cursors. You must close all the cursors after using them.
In your code if any exception occurs in try block, the cursor will not be closed as control will be passed to catch block. Hence modify your code as follows:
try {....}
catch{
}
finally {
cursor.close();
}
It is always a good practice to close the cursor in finally block.
You are not closing cursorid too. Make sure you close cursorid too.
UPDATE 1:
Why and when does this exception occur?
For processing an SQLite statement, a memory area is created by SQLite, known as context area, which contains all information needed for processing the statement, for example, number of rows processed, etc.
A cursor is a pointer to this context area. SQLite controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.
Cursor.close() closes the Cursor, releasing all of its resources and making it completely invalid.
So if you do not close the cursor, the resources most importantly the memory pointed by cursor is not released and it causes leak which in turn causes allocation issues.
Hope it helps.
!Database consists of multiple tables and multiple columns as shown & i have pasted this law.sqlite in assets folder.
Database consists of multiple tables and multiple columns as shown & i have pasted this law.sqlite in assets folder.
Suppose i want to access all the elements of column AS_name as shown . So how should i code for it?
Try this:
Cursor cursor = db.rawQuery("SELECT DISTINCT AS_name FROM Articles",null);
// If you want in order then add "ORDER BY AS_name AESC" in sql query.
cursor.moveToFirst();
while(cursor.moveToNext()) {
// do Something
}
I tried and now the problem is solved :
For anyone facing similar type of problem can try my implementation :
Step 1:
Make a GetterSetter class (named GS here) & generate the Getter-Setters of variables used.
Like in my case:
public class GS {
String AS_name;
public String getAS_name() {
return AS_name;
}
public void setAS_name(String aS_name) {
AS_name = aS_name;
}
}
Step 2:
Make a DBAdapter class which extends SQLiteOpenHelper & in that assign the your name of the file with extension .sqlite !
Rest you need only to copy my DBAdapter.java code & take care to implement the method getData() in which the data from database is fetched !
public class DBAdapter extends SQLiteOpenHelper
{
CustomAdapter adapter;
static String name = "law.sqlite"; //--Replace it with ur sqlite name
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
private DBAdapter(Context v)
{
super(v, name, null, 1);
path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}
public boolean checkDatabase()
{
SQLiteDatabase db = null;
try
{
db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
} catch (Exception e)
{
e.printStackTrace();
}
if (db == null)
{
return false;
}
else
{
db.close();
return true;
}
}
public static synchronized DBAdapter getDBAdapter(Context v)
{
return (new DBAdapter(v));
}
public void createDatabase(Context v)
{
this.getReadableDatabase();
try
{
InputStream myInput = v.getAssets().open(name);
// Path to the just created empty db
String outFileName = path +"/"+ 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();
} catch (IOException e)
{
System.out.println(e);
}
}
public void openDatabase()
{
try
{
sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e)
{
System.out.println(e);
}
}
public ArrayList<GS> getData()
{
try{
Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
gs = new ArrayList<GS>();
while (c1.moveToNext())
{
GS q1 = new GS();
q1.setAS_name(c1.getString(3)); //--- here 3 represents column no.
Log.v("AS_name",q1.AS_name+"");
gs.add(q1);
}
}
catch (Exception e) {
e.printStackTrace();
}
return gs;
}
}
Step 3:
The class MainActivity.java :
public class MainActivity extends Activity {
ArrayList<GS> q = new ArrayList<GS>();
CustomAdapter adapter;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get ListView object from xml
lv = (ListView) findViewById(R.id.listView1);
DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
if (!db.checkDatabase())
{
db.createDatabase(getApplicationContext());
}
db.openDatabase();
q = db.getData();
for(int i=0;i<q.size();i++)
{
Log.i("outside",""+q.get(i).getAS_name());
}
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new CustomAdapter(MainActivity.this,q));
//lv.setAdapter(adapter);
}
class CustomAdapter extends ArrayAdapter<GS>
{
ArrayList<GS> list;
LayoutInflater mInfalter;
public CustomAdapter(Context context, ArrayList<GS> list)
{
super(context,R.layout.customlayout,list);
this.list= list;
mInfalter = LayoutInflater.from(context);
for(int i=0;i<list.size();i++)
{
Log.i("................",""+list.get(i).getAS_name());
}
}
// public int getCount(){
// return list.size();
// }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Log.i("..........","Hello in getView");
if(convertView==null)
{
convertView = mInfalter.inflate(R.layout.customlayout,parent,false);//--customlayout.xml must have a textView
holder = new ViewHolder();
holder.tv1 = (TextView)convertView.findViewById(R.id.textView1);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.tv1.setText(list.get(position).getAS_name());
return convertView;
}
}
static class ViewHolder
{
TextView tv1;
}
}
Run this code & finally the list in the listview will be displayed ! :)
Cursor c = db.query(
TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Specify the table name in TABLE_NAME field. Then access the elements using
c.moveToFirst();
for(int i=0;i<c.getCount();i++)
{
//access elements of column here
long itemId = c.getLong(c.getColumnIndexOrThrow(Column_Name)); //Example with long, corresponding function for string etc also exists.
c.moveToNext();
}
c.close();
Specify the column name in Column_name.
NOTE: If this column is in multiple tables, just put both these code snippets in a loop and iterate through it. May be you can store the table names in an arraylist and access each table in each iteration of the outermost loop. Hope this helps you!!!
I have got these issue, but can not get solutation
Launch timeout has expired, giving up wake lock!
Activity idle timeout for HistoryRecord{44e26a30 com.india.screen/.CategoryList}
This problem get after adding these lines ( String numOfRows="select count(*) from Holyplace_Tbl where State_id='"+stateId+"'";) console nothing print after it
Activity
public class CategoryList extends Activity{
private TableRow holyPlaces,historicalPalces,beach,museum,hills,lakes;
private int stateId;
private AssetDatabaseOpenHelper assetDatabaseHelper;
private Cursor holyplacesCursor,rowsCursor;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.category_screen);
Bundle extras = getIntent().getExtras();
if (extras != null) {
stateId=extras.getInt("stateid");
System.out.println("stateid"+stateId);
}
holyPlaces=(TableRow) findViewById(R.id.holyPlaces);
historicalPalces=(TableRow) findViewById(R.id.historicalPlaces);
museum=(TableRow) findViewById(R.id.museum);
beach=(TableRow) findViewById(R.id.beach);
hills=(TableRow) findViewById(R.id.hills);
lakes=(TableRow) findViewById(R.id.lakes);
assetDatabaseHelper=new AssetDatabaseOpenHelper(CategoryList.this);
assetDatabaseHelper.openDatabase();
assetDatabaseHelper.openReadableMode();
System.out.println("success.....!");
String numOfRows="select count(*) from Holyplace_Tbl where State_id='"+stateId+"'";
System.out.println("rav "+numOfRows);
rowsCursor=assetDatabaseHelper.executeQuery(numOfRows);
System.out.println("hjkdfhfh .............................."+rowsCursor);
System.out.println("hj hi .............................."+rowsCursor);
if(rowsCursor.moveToFirst())
{
System.out.println("hi.........."+rowsCursor.getColumnCount());
do{
int count=rowsCursor.getInt(0);
System.out.println("cu "+count);
System.out.println("cursor.. "+rowsCursor.getCount());
System.out.println("ccccc "+rowsCursor.getInt(0));
System.out.println("jdjhfhf "+rowsCursor.getColumnCount());
}while(rowsCursor.moveToNext());
}
else{
System.out.println("cursor not move");
}
rowsCursor.close();
assetDatabaseHelper.close();
System.out.println("no next value");
}
}
AssetDatabaseOpenHelper.class
public class AssetDatabaseOpenHelper {
private Context context;
private SQLiteDatabase sqliteDatabaseObj;
private String database_name;
private CreateQueries createQueriesObj;
private MySQLiteHelper mySQLitehelperObj;
private int database_version;
private String databaseName="TravelguideDb";
private int databaseVersion=3;
public AssetDatabaseOpenHelper(Context context,String databaseName,int database_version) {
this.context = context;
this.database_name=databaseName;
this.database_version=database_version;
}
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
this.database_name = databaseName;
this.database_version = databaseVersion;
}
public void openDatabase() {
mySQLitehelperObj = new MySQLiteHelper(context, database_name,
database_version);
File dbFile = context.getDatabasePath(database_name);
System.out.println("Assests"+dbFile.exists());
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
}
public void openReadableMode()
{
sqliteDatabaseObj = mySQLitehelperObj.getReadableDatabase();
}
public void openWriteableMode()
{
sqliteDatabaseObj = mySQLitehelperObj.getWritableDatabase();
}
public void close() {
mySQLitehelperObj.close();
}
private void copyDatabase(File dbFile) throws IOException {
OutputStream os = new FileOutputStream(dbFile);
InputStream is = null;
byte[] buffer = new byte[1024];
for(int i=1;i<5;i++)
{
is = context.getAssets().open("TravelguideDb.sqlite.00"+1);
int length;
while ((length=is.read(buffer))!=-1) {
os.write(buffer,0,length);
}
is.close();
}
os.flush();
os.close();
is.close();
}
public Cursor executeQuery(String query)
{
Cursor outputCursor= sqliteDatabaseObj.rawQuery(query, null);
return outputCursor;
}
public void createTable(String tableName, String[] columns, String[] value) {
createQueriesObj = new CreateQueries();
String createTableQuery = createQueriesObj.CreateTableQuery(tableName,
columns, value);
sqliteDatabaseObj.execSQL(createTableQuery);
System.out.println("Query" + createTableQuery);
}
public void deleteTable(String tableName)
{
sqliteDatabaseObj.execSQL("Drop table " + tableName);
}
public void deleteAllDataFromTable(String tableName) {
// truncate table
sqliteDatabaseObj.delete(tableName, null, null);
}
public void deletePerticularRows(String tableName, String whereClause,
String[] whereArgs) {
sqliteDatabaseObj.delete(tableName, whereClause, whereArgs);
}
public Cursor fetchAllRows(String tableName) {
return sqliteDatabaseObj.query(tableName, null, null, null, null, null,
null);
}
public Cursor selectOnWhereCondition(String tableName,
String[] columnsToSelect, String whereColumnName,
String[] whereEqualsTo, String groupBy, String having,
String orderBy) {
return sqliteDatabaseObj.query(tableName, columnsToSelect,
whereColumnName, whereEqualsTo, groupBy, having, orderBy);
}
public void updateRows(String tableName, String[] columnNames,
String[] values, String whereClause, String[] whereArgs)
throws SQLException {
if (columnNames.length != values.length) {
throw new SQLException();
}
ContentValues contentValue = new ContentValues();
int length = values.length;
for (int i = 0; i < length; i++) {
contentValue.put(columnNames[i], values[i]);
}
sqliteDatabaseObj.update(tableName, contentValue, whereClause,
whereArgs);
}
public long addRecords(String TableName, String[] columnNames,
String[] values) throws SQLException {
long result = 0;
if (columnNames.length != values.length) {
throw new SQLException();
} else {
ContentValues contentValues = new ContentValues();
int length = columnNames.length;
for (int i = 0; i < length; i++) {
contentValues.put(columnNames[i], values[i]);
}
result = sqliteDatabaseObj.insert(TableName, null, contentValues);
}
return result;
}
}
public class Breakfast extends Activity implements OnItemClickListener {
DBOpener dbopener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//for fullscreen view
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dinner);
dbopener = new DBOpener(this);
}
// Open the DB, query all subject codes and refresh the listview when app resumes
#Override
protected void onResume() {
super.onResume();
// Configure the listview
ArrayList<String> mealNames = new ArrayList<String>();
ListView lstDine = (ListView)this.findViewById(R.id.dine);
lstDine.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mealNames));
// Open/create the DB
try
{
dbopener.createDatabase(); // Create DB if necessary
dbopener.openDatabase(); // Open the DB
Cursor dinners = dbopener.getBreakfastNames();
while (dinners.moveToNext()) {
mealNames.add(dinners.getString(0)); // Get the Lunch Name & adds to list
}
dinners.close();
// Update the listview
ArrayAdapter<String> ad = (ArrayAdapter<String>)lstDine.getAdapter();
ad.notifyDataSetChanged();
lstDine.setOnItemClickListener(this);
}
catch (Exception e)
{
Toast.makeText(this, "Could not open DB", //Display when Database Cannot be opened
Toast.LENGTH_LONG).show();
}
}
//Close the DB when app pauses
#Override
protected void onPause() {
super.onPause();
dbopener.close();
}
// When user clicks on an item
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
switch(pos)
{
case 0 :
Intent event1 = new Intent("com.edu.tp.iit.mns.Display");
//event1.putExtra("name" , ???);
//event1.putExtra("nutrition" , ???);
//event1.putExtra("rating" , ???);
startActivity(event1);
break;
this is only part of the code. i want to know what should i put inside the (???). its a list view item..so for case 0 i want the name nutrition and rating to be displayed in Display class. and this is my database done using SQLite Database browser.
public class DBOpener extends SQLiteOpenHelper {
private static String DB_PATH =
"/data/data/com.edu.tp.iit.mns/databases/"; //path of our database
private static String DB_NAME ="finals"; // Database name
private final Context myContext;
private SQLiteDatabase db;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public DBOpener(Context context) {
super(context, DB_NAME, null, 1);
myContext = context;
}
public void createDatabase() throws IOException {
boolean dbExists = checkDatabase();
if (dbExists) {
// Do nothing, DB already exists
Log.d("DBOpener", "DB exists");
} else {
// By calling this method an empty database will be created
// in the default system path of your application, which we
// will overwrite with our own database.
Log.d("DBOpener", "DB does not exit - copying from assets");
this.getReadableDatabase();
copyDatabase();
}
}
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
// Try opening the database
String path = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// If it fails, DB does not exist
}
if (checkDB != null)
checkDB.close(); // Close the DB; we don’t need it now
return checkDB != null;
}
private void copyDatabase() throws IOException {
InputStream istream = myContext.getAssets().open(DB_NAME);
OutputStream ostream = new FileOutputStream(DB_PATH + DB_NAME);
// Transfer bytes from istream to ostream
byte[] buffer = new byte[1024];
int length;
while ((length = istream.read(buffer)) > 0) {
ostream.write(buffer, 0, length);
}
// Close streams
istream.close();
ostream.flush();
ostream.close();
}
public void openDatabase() throws SQLiteException {
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (db != null)
db.close();
super.close();
}
// Retrieve all subject codes
public Cursor getDinnerNames() {
if (db == null)
return null;
return db.query("dinner", new String[] {"name"},
null, null, null, null, null);
}
// Get details of specific subject
public Cursor getDinnerDetails(String name) {
if (db == null)
return null;
return db.query("dinner", new String[] {"name", "nutrition", "rating"},
"name = ?", new String[] {name}, null, null, null);
}
// Retrieve all subject codes
public Cursor getLunchNames() {
if (db == null)
return null;
return db.query("lunch", new String[] {"name"},
null, null, null, null, null);
}
// Get details of specific subject
public Cursor getLunchDetails(String name) {
if (db == null)
return null;
return db.query("dinner", new String[] {"name", "nutrition", "rating"},
"name = ?", new String[] {name}, null, null, null);
}
// Retrieve all subject codes
public Cursor getBreakfastNames() {
if (db == null)
return null;
return db.query("breakfast", new String[] {"name"},
null, null, null, null, null);
}
// Get details of specific subject
public Cursor getBreakfastDetails(String name) {
if (db == null)
return null;
return db.query("breakfast", new String[] {"name", "nutrition", "rating"},
"name = ?", new String[] {name}, null, null, null);
}
}
So putExtra() method add extended data to the intent. So you use it when you want to pass data through Activities, you can put all primitive types like float, integer, short or also reference types like String. You can add Bundle object with method putExtras() also other Objects. So you add to intent datatypes you need to.
See this:
Example of add Object to Intent:
Intent intent = new Intent(DownloadingActivity.this, DownloadService.class);
intent.putExtra("url", "http://dl.dropbox.com/u/67617541/DOR0023.rar");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
You should read something about Intent here
So you created ArrayAdapter of Strings and you use getBreakfastNames() that return only name of breakfast so you can add to intent only
String name = (String) parent.getItemAtPosition(pos);
event1.putExtra("name", name);
but i recommend to you create class that extend from for example SimpleCursorAdapter and use design pattern Holder to full control over your data in ListView. It's cleaner, faster.
I have an issue. My database becomes empty after 'Force stop'.
Initially I open empty database, then I`m adding some data. Then I see them in database, they are can be seen in program. But if I restart phone or make "Force stop" of application - everything starts from the very begining.
Here`s my code of DataBaseFactory:
package com.st.nyam.factories;
public class DataBaseFactory {
private SQLiteDatabase db;
private final Context context;
private SD_util sdUtil;
private static String DB_NAME = "nyam_db.db3";
private static String DB_PATH = "/data/data/com.st.nyam/databases/";
private static String TAG = "DataBaseFactory";
//private final String INSERT_RECEPY = "INSERT into RECEPIES ('id', 'recepy', 'author') VALUES (?, ?, ?)";
private final String SELECT_RECIPES = "SELECT * FROM recipes";
private final String SELECT_RECIPE_BY_ID = "SELECT * FROM recipes WHERE ID = ?";
private final String SELECT_COUNT_RECIPE_BY_ID = "SELECT count(*) FROM recipes WHERE ID = ?";
private final String SELECT_STEPS = "SELECT * FROM steps";
private final String SELECT_TABLES = "SELECT name FROM sqlite_master WHERE type= 'table' ORDER BY name";
private final String SELECT_STEPS_BY_ID = "SELECT * FROM steps where recipe_id = ?";
private final String INSERT_STEP = "INSERT INTO steps ('id', 'recipe_id', 'body', 'photo_file_name') VALUES (?,?,?,?) ";
private final String INSERT_RECIPE = "INSERT INTO recipes ('id', 'title', 'description', 'user_id', 'favorites_by', 'main_photo_file_name') VALUES (?,?,?,?,?,?) ";
public DataBaseFactory(Context ctx) {
context = ctx;
sdUtil = new SD_util();
SQLiteDatabase temp_db = ctx.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
temp_db.close();
try {
Log.i(TAG, "Copy intenting");
copyDataBase();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
Log.i(TAG, "Temp created");
if (db == null) {
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
}
Log.i(TAG, "Temp opened");
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch(SQLiteException e){
//database does't exist yet.
e.printStackTrace();
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
public void openDataBase() throws SQLException {
//Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDataBase() throws IOException {
//Open your local db as the input stream
InputStream myInput = context.getAssets().open("db/" + 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);
}
Log.i(TAG, "Copy data");
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public ArrayList<RecipeGeneral> getRecipes() {
ArrayList<RecipeGeneral> recipes = new ArrayList<RecipeGeneral>();
Cursor c = db.rawQuery(SELECT_RECIPES, null);
Log.d(TAG, "getRecipes()");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.d(TAG, "Getting recipe");
RecipeGeneral recipe = ModelUtil.getRecipeFromCursor(c);
recipes.add(recipe);
Log.d(TAG, "Getting recipe added");
} while (c.moveToNext());
}
c.close();
return recipes;
}
public ArrayList<Step> getStepsByRecipeId(int recipeId) throws ParseException {
Log.d(TAG, "In getStepsByRecipe");
ArrayList<Step> steps = new ArrayList<Step>();
Cursor c = db.rawQuery(SELECT_STEPS_BY_ID, new String[]{ Integer.toString(recipeId) });
Log.d(TAG, "Get Query getStepsByRecipe");
try {
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.d(TAG, "Getting step getStepsByRecipe");
Step step = ModelUtil.getStepFromCursor(c);
steps.add(step);
Log.d(TAG, "Getting step added getStepsByRecipe");
} while (c.moveToNext());
}
} finally {
if (c != null) {
c.close();
}
}
c.close();
return steps;
}
/*
public ArrayList<Step> getSteps() throws ParseException {
ArrayList<Step> steps = new ArrayList<Step>();
Cursor c = db.rawQuery(SELECT_STEPS, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Step step = new Step();
step.setId(c.getInt(c.getColumnIndex("id")));
step.setRecipe_id(c.getInt(c.getColumnIndex("recipe_id")));
step.setBody(c.getString(c.getColumnIndex("body")));
step.setPhoto_file_name(c.getString(c.getColumnIndex("photo_file_name")));
step.setPhoto_content_type(c.getString(c.getColumnIndex("photo_content_type")));
step.setPhoto_file_size(c.getInt(c.getColumnIndex("photo_file_size")));
step.setPhoto_updated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("photo_updated_at"))));
step.setCreated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("created_at"))));
step.setUpdated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("updated_at"))));
step.setPhoto_processing(c.getInt(c.getColumnIndex("photo_processing")));
steps.add(step);
} while (c.moveToNext());
}
c.close();
return steps;
}
*/
public ArrayList<Recipe> fetchRecipesByQuery(String query) throws ParseException {
ArrayList<Recipe> recipes = new ArrayList<Recipe>();
Cursor c = db.query(true, "virt", null, "description " + " Match " + "'*" + query + "*'", null,
null, null, null, null);
try{
Log.i(TAG, "Get Query");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.i(TAG, "Getting recipe");
//Recipe recipe = ModelUtil.getRecipeFromCursor(c);
//recipes.add(recipe);
Log.i(TAG, "Getting recipe added");
} while (c.moveToNext());
}
} finally {
if (c != null) {
c.close();
}
}
return recipes;
}
public void addRecipeToFavorites(Recipe recipe, Bitmap bitmap) {
if (!isRecipeExists(recipe.getId())) {
ArrayList<Step> steps = recipe.getSteps();
Log.d(TAG,"Adding recipe to favorites addRecipeToFavorites()");
sdUtil.saveRecipeImage(bitmap, recipe.getImg_url());
db.execSQL(INSERT_RECIPE, new String[] {
Integer.toString(recipe.getId()), recipe.getTitle(),
recipe.getDescription(), recipe.getUser(),
Integer.toString(recipe.getFavorites_by()), recipe.getImg_url()
});
for (Step step : steps) {
Object [] params = new Object[] {step.getImg_url()};
new DownloadImageStep().execute(params);
Log.d(TAG,"Adding step to favorites addRecipeToFavorites()");
addStepToFavorites(step, recipe.getId());
}
} else {
Log.d(TAG,"Recipe already added");
}
}
public void addStepToFavorites(Step step, int recipe_id) {
db.execSQL(INSERT_STEP, new String[]{
Integer.toString(step.getNumber()), Integer.toString(recipe_id),
step.getInstruction(), step.getImg_url(),
});
}
/*
public void putRecepy(Recepy recepy) {
db.execSQL(INSERT_RECEPY, new String[]
{Integer.toString(recepy.getId()),
recepy.getRecepy(), recepy.getAuthor()});
}
*/
public boolean isRecipeExists(int id) {
Cursor c = db.rawQuery(SELECT_RECIPE_BY_ID, new String[]
{Integer.toString(id)});
try {
Log.d(TAG, "isRecipeExists before c.movetoFirst()");
if (c.moveToFirst()) {
if (c != null && c.getCount() > 0) {
Log.d(TAG, "Checking passed");
//Recipe recipe = ModelUtil.getRecipeFromCursor(c);
//Log.d(TAG, "RECIPEExists: " + recipe.toString());
return true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return false;
}
private class DownloadImageStep extends AsyncTask<Object,Void,Object> {
#Override
protected Object doInBackground(Object... o) {
Bitmap outBitmap = null;
try{
sdUtil.saveStepImage((String)o[0]);
}
catch(Exception e){
e.printStackTrace();
}
return outBitmap;
}
}
}
Override the onUpgrade() Method of the SQLiteOpenHelper class and make sure it is empty. That is the place where your database might have been deleted.