!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!!!
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.
Hy guys!
I've got a problem. My app should display all routes in a listview. But there is something wrong with the arrayadapter. If i try my arrayadapter like this:
ArrayAdapter<DefineRoute> adapter = new ArrayAdapter<DefineRoute>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
it works, but it only display the objectname of DefineRoute and i wanna display the output of the cursor.
Ithink i should try:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
But here comes the error: Cannot resolve constructor ArrayAdapter
Here is my Acticity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated constructor stub
super.onCreate(savedInstanceState);
setContentView(R.layout.planausgabelayout);
//Aufruf der TextViews
TextView txtStart = (TextView)findViewById(R.id.txtAusgabeStart);
TextView txtZiel = (TextView)findViewById(R.id.txtAusgabeZiel);
TextView txtZeit = (TextView)findViewById(R.id.txtAusgabeZeit);
intent = getIntent();
txtStart.setText(intent.getStringExtra("StartHaltestelle"));
txtZiel.setText(intent.getStringExtra("ZielHaltestelle"));
txtZeit.setText(intent.getStringExtra("Zeit"));
getRoute();
}
public void getRoute() {
lvList = (ListView)findViewById(R.id.lvList);
Verbindungen verbindungen = new Verbindungen(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
lvList.setAdapter(adapter);
}
Here is my Activity Define Route:
public class DefineRoute {
private String abfahrtszeit;
private String ankunftszeit;
private String dauer;
private String umstieg;
public DefineRoute(String abfahrtszeit, String ankunftszeit, String dauer, String umstieg)
{
this.abfahrtszeit = getAbfahrtszeit();
this.ankunftszeit = getAnkunftszeit();
this.dauer = getDauer();
this.umstieg = getUmstieg();
}
public String getAbfahrtszeit() {
return abfahrtszeit;
}
public String getAnkunftszeit() {
return ankunftszeit;
}
public String getDauer() {
return dauer;
}
public String getUmstieg() {
return umstieg;
}
}
Here is my Activity Verbindungen:
public class Verbindungen {
SQLiteDatabase db;
LinkedList<DefineRoute> route;
DefineRoute[] routeArray;
Context context;
DatabaseHelper myDbHelper = null;
public Verbindungen(Context context) {
route = new LinkedList<DefineRoute>();
this.context = context;
myDbHelper = new DatabaseHelper(context);
}
public DefineRoute[] getVerbindungen() {
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
db = myDbHelper.getReadableDatabase();
// Alle Daten der Datenbank abrufen mithilfe eines Cursors
Cursor cursor = db.rawQuery("SELECT strftime('%H:%M', f.abfahrt) AS Abfahrt," +
"strftime('%H:%M', f.ankunft) AS Ankunft," +
"strftime('%H:%M', strftime('%s',f.ankunft)- strftime('%s',f.abfahrt), 'unixepoch') AS Dauer," +
"r.name AS Route," +
"count(u.fahrt_id) AS Umstiege " +
"FROM scotty_fahrt f " +
"JOIN scotty_haltestelle start ON f.start_id = start.id " +
"JOIN scotty_haltestelle ziel ON f.ziel_id = ziel.id " +
"JOIN scotty_route r ON f.route_id = r.id " +
"LEFT OUTER JOIN scotty_umstiegsstelle u ON f.id = u.fahrt_id " +
"WHERE start.name = 'Linz/Donau Hbf (Busterminal)' " +
"AND ziel.name = 'Neufelden Busterminal (Schulzentrum)' " +
"GROUP BY u.fahrt_id",null);
cursor.moveToFirst();
int i=0;
while (cursor.moveToNext()){
//in this string we get the record for each row from the column "name"
i++;
}
routeArray = new DefineRoute[i];
cursor.moveToFirst();
int k =0;
while (cursor.moveToNext())
{
routeArray[k] = new DefineRoute(cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3));
k++;
}
//here we close the cursor because we do not longer need it
//}
cursor.close();
myDbHelper.close();
return routeArray;
}
please help me.
Now i am creating a ArrayAdapter class where i define my ouput in the listview with:
public class RouteAdapter extends ArrayAdapter<DefineRoute>{
Activity context;
DefineRoute[] defineroute;
public RouteAdapter(Activity context, DefineRoute[] defineroute){
super(context, R.layout.layoutausgabe, defineroute);
this.defineroute = defineroute;
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.layoutausgabe,null);
TextView txZeit = (TextView)row.findViewById(R.id.txZeit);
TextView txDauer = (TextView)row.findViewById(R.id.txDauer);
TextView txUmstieg = (TextView)row.findViewById(R.id.txUmstieg);
DefineRoute defineRoute = defineroute[position];
txZeit.setText(defineRoute.getAbfahrtszeit() + " - " + defineRoute.getAnkunftszeit());
txDauer.setText(defineRoute.getDauer());
txUmstieg.setText(defineRoute.getUmstieg());
return row;
}
}
How should i continue?
and what should my adapter look like?
Your ArrayAdapter<String> is type of String so pass String list to it's constructor instead of verbindungen.getVerbindungen() list of objects.
ArrarAdapter < T > is any type of class you can use
in your case ArrayAdapter so you need override toString method of DefineRoute class
in your case
#Override
public String toString() {
return ankunftszeit+" "+ankunftszeit;
//or what ever you want to displat
}
or there is other Solution is Create your Own adapter extending by BaseAdapter Class.
(this is my lunch.class which populate the listview from database.tell me if there is any mistakes.im still new to this.)
public class Lunch extends Activity implements OnItemClickListener {
DBOpener dbopener;
#Override
protected void onCreate(Bundle savedInstanceState) {
//for fullscreen view
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
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.getLunchNames();
while (dinners.moveToNext()) {
mealNames.add(dinners.getString(0)); // Get the current subj
// code, add 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",
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) {
// Use subject code from listview to retrieve other
// details with the dbopener
switch(pos)
{
case 0 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
newActivity.putExtra("1", "2"); // this is where im unaware of the codes.how to pass the strings of value to the next page
startActivity(newActivity);
break;
}
switch(pos)
{
case 1 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
startActivity(newActivity);
break;
}
switch(pos)
{
case 2 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
startActivity(newActivity);
break;
}
switch(pos)
{
case 3 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
startActivity(newActivity);
break;
}
switch(pos)
{
case 4 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
startActivity(newActivity);
break;
}
switch(pos)
{
case 5 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
startActivity(newActivity);
break;
}
switch(pos)
{
case 6 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
startActivity(newActivity);
break;
}
switch(pos)
{
case 7 :
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
startActivity(newActivity);
break;
}
}
(this is the display.class (image 2) works like a template to display dynamic info like image,food name, food description and its rating.
public class Display extends Activity {
DBOpener dbopener;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
dbopener = new DBOpener(this);
}
#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
Toast.makeText(this, " open DB",
Toast.LENGTH_LONG).show();
Cursor dinners = dbopener.getLunchNames();
while (dinners.moveToNext()) {
// mealNames.add(dinners.getString(0)); // Get the current subj
// code, add 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",
Toast.LENGTH_LONG).show();
}
}
// Close the DB when app pauses
#Override
protected void onPause() {
super.onPause();
dbopener.close();
}
}
and lastly my dpopener file:
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);
}
}
can u help me kick start with the case 0 so that i can complete the code. example, user click BBQ chicken sandwich. it will navigate to display.class and retrieve the info from db and shows image rating and stuffs.
To pass arguments to the new activity via intent you use the putExtra(), like you put on your code:
newActivity.putExtra("1", "2");
The first parameter should be an String constant to identify your parameter, you will use this String to get the value later. The second parameter is the value, android has methods for all the primitives.
On the new activity, you use getExtra("1", "2"), where 1 is the constant you used earlier and 2 is the default value, in case it doesn't finds the value or the constant you used.
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 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 ?