putExtra method values? - android

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.

Related

Getting a unique row in SQLite

I am trying to search an item in sqlite by using String, & trying to return description contained in that row. items are stored in the table named Articles with column name A_name, Description column name is AS_name
This is my code, the cursor is not null, but the while loop is not getting executed once
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
while(cursor.moveToFirst())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("A_name")));
//temp2 =(cursor.getString(cursor.getColumnIndex("AS_name")));
Log.e("running", "id email" +temp+ " name"+temp2);
}
}
return temp;
}
I want to return the corresponding element of AS_name, also I am confused what should I wrote in while loop ?
Can anyone please identify my mistake, Thanks in advance...
UPDATE DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper
{
//CustomAdapter adapter;
static String name = "law6.sqlite";
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;
#Override
public void onCreate(SQLiteDatabase db)
{
}
#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();
/*
InputStream is = v.getAssets().open("quiz.sqlite");
// System.out.println(is.available());
System.out.println(new File(path + "/" + name).getAbsolutePath());
FileOutputStream fos = new FileOutputStream(path + "/" + name);
int num = 0;
while ((num = is.read()) > 0) {
fos.write((byte) num);
}
fos.close();
is.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.setId(c1.getString(0));
q1.setA_id(c1.getString(1));
q1.setA_name(c1.getString(2));
q1.setAS_name(c1.getString(3));
q1.setDesc_art(c1.getString(4));
// q1.setAct(c1.getString(5));
q1.setExtra(c1.getString(6));
q1.setPart(c1.getString(7));
q1.setItalic(c1.getString(8));
Log.v("AS_name",q1.AS_name);
gs.add(q1);
}
}
catch (Exception e) {
e.printStackTrace();
}
return gs;
}
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
Log.v("", ""+cursor.getCount());
while(cursor.moveToNext())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("AS_name")));
// temp2 =(cursor.getString(cursor.getColumnIndex(name)));
Log.e("running", "desc" +temp);
}
}
return temp;
}
}
UPDATE after implementing rajaji answer, I got this error :
try this it will help you
create the raw query for getting the data
public String searchData(String text)
{
String strvalue=null;
SQliteDatabase db=this.getwritabledatabase();
Cursor cur=null;
String strquery="select * from youurtablename where A_name="+text;
cur=db.rawQuery(strquery,null);
if(cur!=null&&cur.moveToFirst())
{
do
{
strvalue=cur.getString(0);
}
while(cur.moveToNext());
}
}
let me inform once you complete
Is your Uri correct??
create Uri depends on your package name and table name, like the code below :
private static final String AUTHORITY = "com.sample.test_db_provider";
private static final String BASE_PATH = "Tables";
private static final Uri Sample_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH
+ "/SampleTable");
Then in your get Method, query the db like the below code with Uri
cur = m_Resolver.query(Sample_URI, new String[] {"A_name","AS_name"},
"SampleTable.A_name = " + text, null, null);
if(cur != null && cur.moveToFirst())
{
do
{
...
}
while(cur.moveToNext());
}
cur.close();
I use the inline where clause but you can do it your way with a parameter. Is this what you are looking for?

Getting a column from .sqlite containing multiple tables with multiple columns

!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!!!

how do i fetch a record from SQL

sorry im kind of a beginner,
I have a simple app that stores data on one page and fetches it on another. i keep getting an error when i try and fetch the data, stating that no such column could be found. please help
this is my code from where i enter the data,
EnterDetails.java
#Override
public void onClick(View arg0) {
EditText holdersala = (EditText) findViewById(R.id.rawsalary);
EditText wantspercentage = (EditText) findViewById(R.id.wantspercent);
EditText needspercentage = (EditText) findViewById(R.id.needspercent);
String holdersalary = holdersala.getText().toString();
final int salary = Integer.parseInt(holdersalary);
String holderwantsp = wantspercentage.getText().toString();
final int wantsp = Integer.parseInt(holderwantsp);
String holderneedsp = needspercentage.getText().toString();
final int needsp = Integer.parseInt(holderneedsp);
if(wantsp + needsp <= 100){
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
databaseAdapter.createRecordS(salary);
databaseAdapter.createRecordW(wantsp);
databaseAdapter.createRecordN(needsp);
databaseAdapter.close();
startActivity(new Intent(EnterDetails.this, Summary.class));
} else {
}
Toast toast = Toast.makeText(EnterDetails.this, "incorrect data", 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
code from where i fetch the data
TextView bn = (TextView) findViewById(R.id.budget_need);
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
bn.setText(databaseAdapter.fetchRecordS(1));
databaseAdapter.close();
and code from my databaseAdapter.java
public class DatabaseAdapter {
private Context context;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
this.context = context;
}
public DatabaseAdapter open() throws SQLException {
dbHelper = new DatabaseOpenHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createRecordS(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("salafig", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordN(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("needsper", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordW(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("wantsper", interger);
return database.insert("maindata", null, contentValue);
}
public int fetchRecordS(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "salafig"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}
public int fetchRecordW(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "wantsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}public int fetchRecordN(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "needsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
hope it makes sense thanks if advance for any help.
Look at HEREto check the correct syntax of the SQLiteDatabase query method.
The forth parameter of the method is the selection condition, it s supposed to be something like:
"salafig = "+ rowId"
instead of this :
"salafig"+ rowId"

How to pass data from sqlite listview to new intent?

(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.

How to access more than one database table data in android?

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 ?

Categories

Resources