Load different values from a database column - android

How I can get a different values from a column with the same name (like the photo)?
In the photo, "test" have a 3 differents values, how I can load them to a ListView or a Spinner?
I have this code, works, but don't get the 3 values, only first value:
MainActivity
public void lookupProduct (View view) {
DatabaseHandler dbHandler = new DatabaseHandler(getApplicationContext());
Name name = dbHandler.findProduct(spinner.getSelectedItem().toString());
Toast.makeText(this, spinner.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
Intent j = new Intent(view.getContext(), SubActivity.class);
Bundle dados = new Bundle();
if (name != null) {
inputLabel.setText(String.valueOf(name.getName()));
values.setText(String.valueOf(name.getValue()));
// Passar para SubActivity
dados.putString("name", String.valueOf(name.getName()));
dados.putString("value", String.valueOf(name.getValue()));
} else {
inputLabel.setText("No Match Found");
dados.putString("name","No Match Found" );
dados.putString("value", "No Match Found");
}
j.putExtras(dados);
startActivity(j);
}
DatabaseHelper
public Name findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Name names = new Name();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
cursor.close();
} else {
names = null;
}
db.close();
return names;
}
NameClass
public class Name {
private int _id;
private String _name;
private String _value;
public Name() {
}
public Name(int id, String name, String value) {
this._id = id;
this._name = name;
this._value = value;
}
public Name(String name, String value) {
this._name = name;
this._value = value;
}public String getName() {
return this._name;
}
public String getValue() {
return this._value;
}

Try this
Name names = new Name();
ArrayList<Name > listaName= new ArrayList<>();//create an arraylist of your
custom objects
if (cursor.moveToFirst()) {
do {
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
listaName.add(names);//add your object to arraylist(you were overriding the object.)
} while (cursor.moveToNext());
cursor.close();
//AND ALSO CLOSE DB:
db.close
EDIT 2: Try this and change your --> String Query = "Select * from "+TABLE_NAME;
for ( int i= 1; i< listaName.size(); i++ ) {
System.out.println(listaName.get(i).getName());
}
Your problem:
public Name findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Name names = new Name();
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // this is not necessary because on the top line,
you put it in that position
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
cursor.close(); // You should not close until it is
completely used
} else {
names = null;
}
db.close();
return names;
}
And to read all the cursor is necessary to use a do-while method
If you have any problems, you can ask me again

Though not yet tested, you can try this:
// fetch data from DB
public ArrayList<Name> findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
ArrayList<Name> listOfNames= new ArrayList<>();
if (cursor.moveToFirst()) {
do {
listOfNames.add(new Name(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2)));
} while (cursor.moveToNext());
cursor.close();
db.close
return listOfNames;
}
// add data on spinner
public void addItemsOnSpinner() {
Spinner mSpinner = (Spinner) findViewById(R.id.mSpinner);
ArrayList<String> list = new ArrayList<String>();
for(Name name: findProduct("test")){
list.add(name.getValue());
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(dataAdapter);
}

Related

How to iterate and retrieve over all data stored in sqlite database

I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.

Get single record from Inner Joins SQLite

I am new to android programming. I am having a little issue on how to retrieve a single record while using Inner joins. From research I know how to do it with one table e.g
public Shop getShop(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SHOPS, new String[] { KEY_ID,
KEY_NAME, KEY_SH_ADDR }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Shop contact = new Shop(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return shop
return contact;
}
But I am at a loss when I have to consider three different tables. I have been able to retrieve all records, currently my code to retreive a single record is below. I have been able to replace ? with a corresponding id and it works but I obviously do not want to have that static.
getTeam method
//Getting Single Team
public List < Team > getTeam() {
List < Team > teamList = new ArrayList < Team > ();
// Select All Query
String selectQuery = "SELECT teams.id, teams.team_name, teams.image, teams_vs_leagues.points, leagues.league_name " +
"FROM teams_vs_leagues " +
"INNER JOIN teams " +
"ON teams_vs_leagues.team_id = teams.id " +
"INNER JOIN leagues " +
"ON teams_vs_leagues.league_id = leagues.id " +
"WHERE teams.id = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Team team = new Team();
team.setId(Integer.parseInt(cursor.getString(0)));
team.setTeamName(cursor.getString(1));
team.setPath(cursor.getString(2));
team.setPoints(Integer.parseInt(cursor.getString(3)));
team.setLeagueName(cursor.getString(4));
// Adding team to list
teamList.add(team);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return team list
return teamList;
}
Team class
public class Team {
String team_name, path, league_name;
int id, league_id, points;
public Team(int keyId, String team_name, String path,
int points, String league_name) {
this.id = keyId;
this.team_name = team_name;
this.path = path;
this.points = points;
this.league_name = league_name;
}
public Team() {}
public Team(int keyId) {
this.id = keyId;
}
public int getId() {
return id;
}
public void setId(int keyId) {
this.id = keyId;
}
public int getLeagueId() {
return league_id;
}
public String getTeamName() {
return team_name;
}
public String getLeagueName() {
return league_name;
}
public void setLeagueName(String league_name) {
this.league_name = league_name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public void setTeamName(String team_name) {
this.team_name = team_name;
}
public void setLeague_id(int league_id) {
this.league_id = league_id;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
Since you are using placeholder
"WHERE teams.id = ?";
in your query , you need to pass selection arguments in rawQuery() so that during the execution of your query , the placeholder will be replaced by the actual value.
Cursor cursor = db.rawQuery(selectQuery, new String[]{id});//"id" is the value which you want to pass in place of "?". You can hardcode it or you can pass it all the way to getTeam()
Check this .

fetch data from a dbHandler.java file but not able to show it in listview?

I did some changes in my code and it runs but I didn't get appropriate output. I create a method.
public void fetchData() {
dbHandler = new CourseDbHandler(this,null,null,1);
List<CreateCourse> course_data = dbHandler.getdata();
String[] data = new String[course_data.size()];
int i=0;
for(CreateCourse co : course_data)
{
data[i] = co.getCourseSelected();
i++;
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
in this method i used dbHandler.getdata method, which is as follows
public List<CreateCourse> getdata() throws NullPointerException {
String dbString = "";
String course;
String sec;
List<CreateCourse> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
course = c.getString(1);
sec = c.getString(2);
dbString = course+" "+sec;
CreateCourse co = new CreateCourse();
co.setCourseSelected(dbString);
list.add(new CreateCourse(c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
These are the getter and setter method
public void setCourseSelected(String courSelected) {
courseSelected = courSelected;
}
public String getCourseSelected() {
System.out.println(courseSelected);
return courseSelected;
}
It gives an error unfortunately app has stopped.
Create a class with your data:
public class Course {
public String id;
public String course;
public String sec;
public Course (String id, String course, String sec) {
this.id = id;
this.course = course;
this.sec = sec;
}
Then modify your method to return List of your data:
public List<Course> getdata() throws NullPointerException {
List<Course> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
list.add(new Course(c.getString(0), c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
Then you can use this List with ArrayAdapter to show your data in ListView.
I changed all the code and solve my problem in above code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_course);
dbHandler = new CourseDbHandler(this, null, null, 1);
Cursor c = dbHandler.getData();
c.moveToFirst();
// System.out.println("Select");
if(c.equals(null)){
System.out.println("NO DATA");
}
else {
if(c.moveToFirst()) {
do {
dbString=null;
course = c.getString(1);
sec = c.getString(2);
dbString = course + " " + sec;
courseItem.add(dbString);
} while (c.moveToNext());
}
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, courseItem);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
Thank you for your help..

Display SqLite Select value in textfield

I'm trying to display SQLite table value in text field. This is my code, but it's not working. I have table(SAP_DRQ_TABLE ) with two fields(SAP_DRQ_KEY_METROLAC ,SAP_DRQ_KEY_DRC).
DBHelper.java
private static final String SAP_DRQ_TABLE = "sap_drq";
public static final String SAP_DRQ_KEY_METROLAC = "metrolac";
public static final String SAP_DRQ_KEY_DRC= "drc";
public List<SAP_DRQDatamodel> SAP_DRQDatamodel() {
// TODO Auto-generated method stub
List<SAP_DRQDatamodel> drc = new ArrayList<SAP_DRQDatamodel>();
// Select All Query
String selectQuery = "SELECT * FROM " + SAP_DRQ_TABLE +" where"+SAP_DRQ_KEY_METROLAC+"='50'" ;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
SAP_DRQDatamodel codes = new SAP_DRQDatamodel();
codes.setdrc(cursor.getString(cursor.getColumnIndex(SAP_DRQ_KEY_DRC)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return drc;
}
dashbord.java
DBHelper db = new DBHelper(getApplicationContext());
List<SAP_DRQDatamodel> DRQval= db.SAP_DRQDatamodel();
for (SAP_DRQDatamodel DRQ : DRQval){
mDRQ.setText(DRQ.getdrc());
}
SAP_DRQDATAMODEL
public class SAP_DRQDatamodel {
public String getmetrolac() {
return metrolac;
}
public void setmetrolac(String metrolac) {
this.metrolac = metrolac;
}
public String getdrc() {
return drc;
}
public void setdrc(String drc) {
this.drc = drc;
}
public String metrolac="", drc="";
}
problem is woth your select query
String selectQuery = "SELECT * FROM " + SAP_DRQ_TABLE +" where "+SAP_DRQ_KEY_METROLAC+"='50'"

How to retrieve data from database in android Creating database on SqliteBrowser

I have jokes.db database. This database file imported from using this article., http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/. Now i have Jokes.db in to /data/data/a.b.c/database/Jokes.db. In this database , I have two table NepaliJokes and EnglishJokes. So Now I want to retrive this nepali and english jokes and display in to textview, But I have done following code but couldnot more idea behind How to retrieve data from database.
public class FunnyJokes extends Activity implements View.OnClickListener {
private SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
Button back;
super.onCreate(savedInstanceState);
setContentView(R.layout.displayjoks1);
back = (Button) findViewById(R.id.back_btn);
back.setOnClickListener(this);
DataBaseHelper helper = new DataBaseHelper(this);
database = helper.getWritableDatabase();
loadJokes();
}
private void loadJokes() {
//jok=new ArrayList<String>();
/*Cursor c = database.query("SELECT title,body" +
" FROM " + 'tableName'
+ " WHERE category=1;",
null);*/
Cursor c = database.query("NepaliJokes",
null, null, null, null, null, null);
c.moveToPosition(0);
TextView tv= (TextView) findViewById(R.id.textView1);
tv.append(c.getString(1));
c.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_btn:
FunnyJokes.this.finish();
break;
default:
break;
}
}
}
I also use the database file import from in DDMS->fileExploer. I import database file Pull mobile icon from left of file explorer section.
To read values from the table:
Create a cursor to read data from the database.
Write the following function.
public Cursor retrieveRecords(int category)
{
Cursor c = null;
c = db.rawQuery("select title,body from tablename where category=" +category, null);
return c;
}
Now get the values from the cursor.
public void getDataFromDatabase()
{
try
{
Cursor cursor = null;
db.OpenDatabase();
cursor = db.retrieveRecords();
if (cursor.getCount() != 0)
{
if (cursor.moveToFirst())
{
do
{
titleArrayList.add(cursor.getString(cursor.getColumnIndex("title")));
bodyArrayList.add(cursor.getString(cursor.getColumnIndex("body")));
} while (cursor.moveToNext());
}
db.closeDatabase();
}
cursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I an using the fallowing class for manage DataBase in my application.
public class PersonDbHelper {
public class Row_DocumentTable extends Object {
public int rwo_id;
public String dockey;
public String docid;
public String size;
public String status;
public String name;
public String product_discription;
public String type;
public String publisher;
public String version;
public String filepathurl;
public String basepage;
public String copypaste;
public String save;
public String print;
public String printablepage;
public String nonprintablepage;
public String search;
public String watermarkimageurl;
public String expiry;
public String versiondescription;
public String update_available;
public String localfilepath;
}
public class Row_CategoriesTable extends Object {
public String dockey;
public String category_id;
public String category_name;
}
private static final String DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.DOCUMENTDETAIL";
private static final String DROP_CATEGORIES_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.CATEGORIES";
private static final String DATABASE_CREATE_DOCUMENTDETAIL = "create table DOCUMENTDETAIL(row_id integer primary key autoincrement, dockey text , "
+ "docid text not null,"
+ "size text not null,"
+ "status text not null,"
+ "name text not null,"
+ "product_discription text not null,"
+ "type text not null,"
+ "publisher text not null,"
+ "version text not null,"
+ "filepathurl text not null,"
+ "basepage text not null,"
+ "copypaste text not null,"
+ "save text not null,"
+ "print text not null,"
+ "printablepage text not null,"
+ "nonprintablepage text not null,"
+ "search text ,"
+ "watermarkimageurl text not null,"
+ "expiry text not null,"
+ "versiondescription text not null,"
+ "update_available text not null,"
+ "localfilepath text not null"
+ ");";
private static final String DATABASE_CREATE_CATEGORIES = "create table CATEGORIES(_id integer primary key autoincrement, "
+ "dockey text ,"
+ "category_id text ,"
+ "category_name text"
+ ");";
private static final String DATABASE_NAME = "CONTENTRAVENDB";
private static final String DATABASE_TABLE1 = "CATEGORIES";
private static final String DATABASE_TABLE2 = "DOCUMENTDETAIL";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public PersonDbHelper(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
db.execSQL(DATABASE_CREATE_DOCUMENTDETAIL);
db.execSQL(DATABASE_CREATE_CATEGORIES);
}
public void dropAllTable(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
// db.execSQL(DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE);
// db.execSQL(DROP_CATEGORIES_TABLE_FROM_DATABASE);
db.delete(DATABASE_TABLE1, null, null);
db.delete(DATABASE_TABLE2, null, null);
close();
}
public PersonDbHelper(Context ctx, String abc) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
}
public PersonDbHelper() {
}
public void close() {
db.close();
}
public void createRow_InDocumentDetailTable(String dockey, String docid,
String size, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available,
String localfilepath) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("docid", docid);
initialValues.put("size", size);
initialValues.put("status", status);
initialValues.put("name", name);
initialValues.put("product_discription", product_discription);
initialValues.put("type", type);
initialValues.put("publisher", publisher);
initialValues.put("version", version);
initialValues.put("filepathurl", filepathurl);
initialValues.put("basepage", basepage);
initialValues.put("copypaste", copypaste);
initialValues.put("save", save);
initialValues.put("print", print);
initialValues.put("printablepage", printablepage);
initialValues.put("nonprintablepage", nonprintablepage);
initialValues.put("search", search);
initialValues.put("watermarkimageurl", watermarkimageurl);
initialValues.put("expiry", expiry);
initialValues.put("versiondescription", versiondescription);
initialValues.put("update_available", update_available);
initialValues.put("localfilepath", localfilepath);
db.insert(DATABASE_TABLE2, null, initialValues);
}
public void createRow_InCategorieTable(String dockey, String category_id,
String category_name) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("category_id", category_id);
initialValues.put("category_name", category_name);
db.insert(DATABASE_TABLE1, null, initialValues);
}
public void deleteRow_FromDocumentDetailTable(long rowId) {
db.delete(DATABASE_TABLE2, "_id=" + rowId, null);
}
public List<Row_DocumentTable> fetchAllRows_FromDocumentDetailTable() {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL";
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "row_id","dockey","docid","size", "status", "name",
// "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry",
// "versiondescription","update_available","localfilepath"
// }, null, null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_DocumentTable> fetchAllRows_Of_Single_Type(String argtype) {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL where type='" + argtype
+ "'";
Cursor c = db.rawQuery(sql, null);
// Cursor c=db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"
// }, "type=PDF", null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_CategoriesTable> fetchAllRows_FromCategorieTable(
String argsql) {
ArrayList<Row_CategoriesTable> ret = new ArrayList<Row_CategoriesTable>();
try {
String sql = argsql;
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(true,DATABASE_TABLE1, new String[] {
// "dockey","category_id","category_name"
// }, null,null,null, null, null,null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_CategoriesTable row = new Row_CategoriesTable();
row.dockey = c.getString(0);
row.category_id = c.getString(0);
row.category_name = c.getString(0);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public Row_DocumentTable fetchRow_FromDocumentDetailTableByDocKey(
String dockey) {
Row_DocumentTable row = new Row_DocumentTable();
String sql = "select * from DOCUMENTDETAIL where dockey='" + dockey
+ "'";
try {
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"},
// "dockey=" + dockey, null, null,
// null,null,"name desc");
if (c.getCount() > 0) {
c.moveToFirst();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
return row;
} else {
row.docid = null;
row.dockey = row.name = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
return row;
}
public void updateRow_InDocumentDetailTableByDocKey(String dockey,
String docid, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available) {
ContentValues args = new ContentValues();
args.put("dockey", dockey);
args.put("docid", docid);
args.put("status", status);
args.put("name", name);
args.put("product_discription", product_discription);
args.put("type", type);
args.put("publisher", publisher);
args.put("version", version);
args.put("filepathurl", filepathurl);
args.put("basepage", basepage);
args.put("copypaste", copypaste);
args.put("save", save);
args.put("print", print);
args.put("printablepage", printablepage);
args.put("nonprintablepage", nonprintablepage);
args.put("search", search);
args.put("watermarkimageurl", watermarkimageurl);
args.put("expiry", expiry);
args.put("versiondescription", versiondescription);
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public Cursor GetAllRows() {
try {
return db.query(DATABASE_TABLE2, new String[] { "dockey", "docid",
"status", "name", "product_discription", "type",
"publisher", "version", "filepathurl", "basepage",
"copypaste", "save", "print", "printablepage",
"nonprintablepage", "search", "watermarkimageurl",
"expiry", "versiondescription" }, null, null, null, null,
null);
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
return null;
}
}
public void updateRow_InDocumentDetailTableByDocKey_UpdateAvl(Context ctx,
String dockey, String update_available) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public void updateRow_InDocumentDetailTableByDocKey_LocalFilePath(
Context ctx, String dockey, String argLocalFilePath) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("localfilepath", argLocalFilePath);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
}
I have two table and apply all the query insert update delete and createtable select using the code it is working fine.
I hope this is help.
First of all don't use tv.append instead use setText because if u use append then ur next joke will be append to the previous one and textView show the jokes as you click the button
Actually the answere is long enough so
I have written a ansere in my blog please see the link the code will do exactly what you are lokking for but i just made one table you can add more table similarly.
You can visit HERE

Categories

Resources