Why won't sqlite database open? - android

I am following a tutorial, and trying to create a database, then add put texts into the database, but the application crashes when it reaches ".open()"
public class SmsReceiver extends BroadcastReceiver
{
CommentsDataSource datasource;
#Override
public void onReceive( Context context, Intent intent )
{
Log.d("tag", "0");
datasource = new CommentsDataSource(this);
Log.d("tag", "1");
datasource.open();
Log.d("tag", "2");
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
//String str = "";
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String str = msgs[i].getOriginatingAddress();
//str += " :";
String str2 =msgs[i].getMessageBody().toString();
//str += "\n";
Log.d("tag", "3");
abortBroadcast();
Log.d("tag", "4");
String From = "Send: " + str + " Message: " + str2;
Log.d("tag", "5");
TestDatabaseActivity Test = new TestDatabaseActivity();
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) Test.getListAdapter();
Comment comment;
Log.d("tag", "6");
String[] comments = new String[] { From };
Log.d("tag", "7");
int nextInt = new Random().nextInt(3);
Log.d("tag", "8");
// Save the new comment to the database
comment = datasource.createComment(comments[nextInt]);
Log.d("tag", "9");
adapter.add(comment);
Log.d("tag", "10");
datasource.close();
break;
}
}
}
}
and here is the database:
public class CommentsDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_COMMENT };
public CommentsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public CommentsDataSource(SmsReceiver smsReceiver) {
// TODO Auto-generated constructor stub
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Comment createComment(String comment) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
long insertId = database.insert(MySQLiteHelper.TABLE_COMMENTS, null,
values);
// To show how to query
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
return cursorToComment(cursor);
}
public void deleteComment(Comment comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
}
logcat gets to tag 0 then 1, then it says "Unable to start receiver"
What's going on, and why won't it open?

replace this with context in constructor:
datasource = new CommentsDataSource(this);
to
datasource = new CommentsDataSource(context);

Related

Display each row from Database on a new line in a TextView

I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}

inserting and view sqlite database error

I have a broadcastreceiver to detect incoming sms and I'm storing the sms's in sqlite database. Then I'm trying to view the database content using query. The code was working perfectly when I wasn't using "id INTEGER PRIMARY KEY AUTOINCREMENT". After adding "id", when I try to view database content, its showing "No records found". So either its not entering values properly or there is error in view query code. I searched in other posts but not able find the error. Any help in this would be really helpful.
Broadcastreceiver:
public class MyBroadcast extends BroadcastReceiver{
Context mContext;
String msg_body;
String mob_no, name;
String dttm, key;
SQLiteDatabase db;
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
db=context.openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
StringBuffer content = new StringBuffer();
if (messages.length > 0) {
for (int i = 0; i < messages.length; i++) {
content.append(messages[i].getMessageBody());
mob_no = messages[i].getOriginatingAddress();
Calendar calendar = Calendar.getInstance();
Date finaldate = calendar.getTime();
dttm = finaldate.toString();
}
}
msg_body = content.toString();
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mob_no));
Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
try {
if(c.moveToFirst()){
name = c.getString(0);
db.execSQL("INSERT INTO student (sender, timestamp, mesg) VALUES('"+name+"','"+dttm+"','"+msg_body+"');");
}else{
db.execSQL("INSERT INTO student (sender,timestamp,mesg) VALUES('"+mob_no+"','"+dttm+"','"+msg_body+"');");
}
} catch (Exception e) {
// TODO: handle exception
}finally{
c.close();
}
}
}
}
MainActivity:
public class MainActivity extends Activity {
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, timestamp TEXT, mesg TEXT);");
} //oncreate
public void ViewAll(View v){
try{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Sender: "+c.getString(1)+"\n");
buffer.append("TimeStamp: "+c.getString(2)+"\n");
buffer.append("Mesg: "+c.getString(3)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void Delete(View v){
Cursor c=db.rawQuery("SELECT * FROM student WHERE id=(SELECT MIN(id) FROM student)", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE id=(SELECT MIN(id) FROM student)");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Entry");
}
}
private void showMessage(String title, String message) {
// TODO Auto-generated method stub
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
} //activty

Sent messages are shown duplicated in my List View

private class getItemLists extends AsyncTask<Void, String, String> {
private Context mContext;
public getItemLists(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
ld.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Intent i = new Intent("notify.intent.MAIN");
// mContext.sendBroadcast(i);
}
#Override
protected String doInBackground(Void... params) {
try {
Chatdb db = new Chatdb(mContext);
String[] smsid = db.getAllinboxsmsid();
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body",
"date", "read" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = mContext.getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
boolean exists = false;
if (c.moveToLast()) {
do {
exists = false;
publishProgress((c.getCount() - c.getPosition() + ";" + c
.getCount()));
for (int x = 0; x < smsid.length; x++) {
if (smsid[x].equals(c.getString(0))) {
exists = true;
}
}
if (!exists) {
if (c.getString(4).equals("0")) {
smsRead = "1";
} else {
smsRead = "0";
}
db.addMsgWithTime(c.getString(1), c.getString(2),
"1", "0", "L", c.getString(0),
c.getString(3), smsRead);
publishProgress((c.getCount() - c.getPosition()
+ ";" + c.getCount()));
// Intent in = new
// Intent("SmsMessage.intent.MAIN").putExtra(
// "get_msg", c.getString(1));
//
// // You can place your check conditions here(on
// the SMS or the
// // sender)
// // and then send another broadcast
// SuperMain.this.sendBroadcast(in);
}
} while (c.moveToPrevious());
}
// c.close();
//
String[] SentSmsId = db.getAllsentsmsid();
Uri sentURI = Uri.parse("content://sms/sent");
// List required columns
String[] reqColsSent = new String[] { "_id", "address", "body",
"date", "read" };
// Get Content Resolver object, which will deal with Content
// Provider
// Fetch Inbox SMS Message from Built-in Content Provider
c = cr.query(sentURI, reqColsSent, null, null, null);
if (c.moveToLast()) {
do {
exists = false;
publishProgress((c.getCount() - c.getPosition() + ";" + c
.getCount()));
for (int x = 0; x < SentSmsId.length; x++) {
if (SentSmsId[x].equals(c.getString(0))) {
exists = true;
}
}
if (!exists) {
db.addMsgWithTime(c.getString(1), c.getString(2),
"0", "0", "S", c.getString(0),
c.getString(3), "1");
// db.close();
publishProgress((c.getCount() - c.getPosition()
+ ";" + c.getCount()));
}
} while (c.moveToPrevious());
}
c.close();
db.close();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
return "done";
}
#Override
protected void onPostExecute(String done) {
super.onPostExecute(done);
// Toast.makeText(mContext, "Messages have synced successfully",
// 3).show();
ld.setVisibility(View.INVISIBLE);
}
}
This is my Loading procedure of Inbox and Sent messages and showing at mu list view.
here ld is my loader... showing when data is loading
public String[] getAllsentsmsid() {
String selectQuery = "SELECT " + KEY_SMSID + " FROM " + TABLE_THREAD
+ " WHERE " + KEY_SMSID + "<>'0' AND " + KEY_ORIGIN + "='0'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] allid = new String[cursor.getCount()];
int x = 0;
if (cursor.moveToFirst()) {
do {
allid[x] = cursor.getString(0);
x++;
} while (cursor.moveToNext());
}
db.close();
return allid;
}
public String[] getAllinboxsmsid() {
String selectQuery = "SELECT " + KEY_SMSID + " FROM " + TABLE_THREAD
+ " WHERE " + KEY_SMSID + "<>'0' AND " + KEY_ORIGIN + "='1'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] allid = new String[cursor.getCount()];
int x = 0;
if (cursor.moveToFirst()) {
do {
allid[x] = cursor.getString(0);
x++;
} while (cursor.moveToNext());
}
db.close();
return allid;
}
These are my database methods where I am storing messages id and save them in my database.
In my list view making duplicate threads of chatting.

android: push sms As recieved in inbox using getContentResolver

on sms received , i have saved that sms in my database
now i want to move that sms into inbox
i used this code but it move it as sent by me
please help me to move it as a received sms
ListViewLogItem lm = listArray.get(position);
long datein = Long.parseLong(lm.getInboxTime());
Uri uri = Uri.parse("content://sms/");
ContentValues cv2 = new ContentValues();
cv2.put("address","+"+lm.getNumber());
cv2.put("date", datein);
cv2.put("read", 1);
cv2.put("type", 2);
cv2.put("body", lm.getSms());
getContentResolver().insert(Uri.parse("content://sms/inbox"), cv2);
Change:
cv2.put("type", 2);
To:
cv2.put("type", 1);
Because:
public static final int MESSAGE_TYPE_INBOX = 1;
public static final int MESSAGE_TYPE_SENT = 2;
You can use following method for deleting SMS from Inbox,
private void deleteMessage()
{
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
//c.moveToFirst();
while (c.moveToNext())
{
System.out.println("Inside if loop");
try
{
String address = c.getString(2);
String MobileNumber = mainmenu.getParameterData().getMobileNumber().trim();
//Log.i( LOGTAG, MobileNumber + "," + address );
Log.i( LOGTAG, c.getString(2) );
if ( address.trim().equals( MobileNumber ) )
{
String pid = c.getString(1);
String uri = "content://sms/conversations/" + pid;
getContentResolver().delete(Uri.parse(uri), null, null);
stopSelf();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Use thisvalues.put("status", SmsManager.STATUS_ON_ICC_UNREAD); . Status can be anything like read/unread/seen. I have keep it as unread.
Look at Message status
values.put("read", true); // As Read
and
values.put("read", false); // As Un Read
public class Message {
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
#SuppressWarnings("unused")
private ContentResolver resolver;
public Message(ContentResolver ConResolver){
resolver = ConResolver;
}
public String getMessage(int batas) {
Cursor cur = resolver.query(SMS_INBOX, null, null, null,null);
String sms = "Message >> \n";
int hitung = 0;
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
if(hitung == batas)
break;
hitung++;
}
return sms;
}
public int getMessageCountUnread(){
Cursor c = resolver.query(SMS_INBOX, null, "read = 0", null, null);
int unreadMessagesCount = c.getCount();
c.deactivate();
return unreadMessagesCount;
}
public String getMessageAll(){
Cursor cur = resolver.query(SMS_INBOX, null, null, null,null);
String sms = "Message >> \n";
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
}
return sms;
}
public String getMessageUnread() {
Cursor cur = resolver.query(SMS_INBOX, null, null, null,null);
String sms = "Message >> \n";
int hitung = 0;
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
if(hitung == getMessageCountUnread())
break;
hitung++;
}
return sms;
}
public void setMessageStatusRead() {
ContentValues values = new ContentValues();
values.put("read",true);
resolver.update(SMS_INBOX,values, "_id="+SmsMessageId, null);
}
}

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