TextView not populating data from sqlite - java

I am trying to create a bill template by populating data stored in SQLite. I know there is a way to do this using ListView as well. The app crashes when I run this Activity.
public class Ticket_generator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ticket_table);
Context context;
context=this;
TableHelper datahelper= new TableHelper(context);
datahelper.insertData("Home foods","Veg Resturant","New Municipal Blog","abc compound","mumbai 400007","01/07/17","COUNTER","BILL NO.-123","Perticulars","Quantity","Rate","gst","06.56AM");
Cursor cr;
cr=datahelper.getInformation();
TextView tv;
tv=(TextView)findViewById(R.id._s1t1);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5, 5, 5, 5);
tv.setText(cr.getString(1));
}
}
This is the TableHelper.java
public class TableHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Ticketdb";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_TICKET = "tblticketdata";
public static final String CREATE_TABLE_TICKET = "CREATE TABLE IF NOT EXISTS " + TABLE_TICKET + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, s1t1 TEXT NULL,s1t2 TEXT NULL,s1t3 TEXT NULL,s1t4 TEXT NULL,s1t5 TEXT NULL,s2t1 TEXT NULL,s2t2 TEXT NULL,s2t3 TEXT NULL, s3t1 TEXT NULL,s3t2 TEXT NULL,s3t3 TEXT NULL,ft1 TEXT NULL,ft2 TEXT NULL)";
public static final String DELETE_TABLE_SERVICES = "DROP TABLE IF EXISTS " + TABLE_TICKET;
public TableHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TICKET);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DELETE_TABLE_SERVICES);
//Create tables again
onCreate(db);
}
public void insertData(String s1t1, String _s1t2, String _s1t3, String _s1t4, String _s1t5, String _s2t1, String _s2t2,
String _s2t3, String _s3t1, String _s3t2, String _s3t3, String _ft1, String _ft2) {
// Open the database for writing
SQLiteDatabase db = this.getWritableDatabase();
// Start the transaction.
db.beginTransaction();
ContentValues values;
try {
values = new ContentValues();
values.put("s1t1", s1t1);
values.put("s1t2", _s1t2);
values.put("s1t3", _s1t3);
values.put("s1t4", _s1t4);
values.put("s1t5", _s1t5);
values.put("s2t1", _s2t1);
values.put("s2t2", _s2t3);
values.put("s2t3", _s2t3);
values.put("s3t1", _s3t1);
values.put("s3t2", _s3t2);
values.put("s3t3", _s3t3);
values.put("ft1", _ft1);
values.put("ft2", _ft2);
// Insert Row
long i = db.insert(TABLE_TICKET, null, values);
Log.i("Insert", i + "");
// Insert into database successfully.
db.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
public Cursor getInformation() {
SQLiteDatabase sq = this.getReadableDatabase();
String[] columns = {"s1t1", "s1t2", "s1t3", "s1t4", "s1t5", "s2t1", "s2t2", "s2t3", "s3t1", "s3t2", "s3t3", "ft1", "ft2"};
Cursor cr = sq.query(TABLE_TICKET, columns, null, null, null, null, null);
return cr;
}
}

You need to move your cursor for the first position, like this example:
public String getFirstResult(){
String firstResult;
TableHelper datahelper = new TableHelper(context);
Cursor cursor = datahelper.getInformation();
cursor.moveToFirst();
firstResult = cursor.getString(0);
return firstResult;
}

Related

ANDROID: Get n rows from SQLite Database using Swipe to Refresh

I'm new to android programming. I'm still practicing and making this simple app.
I want to get 2 rows per refresh from SQLite Database and display on a listview.
But what I am getting now is the first 2 rows again and again.
My database already has data with 6 rows.
What I don't know is how to pass offset to the Database Operation and how to get the next 2 rows.
Thank you so much for your time. I hope someone can help me.
Pls see my code below:
DisplayItem.java
public class DisplayItem extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private String TAG = DisplayItem.class.getSimpleName();
private SwipeRefreshLayout swipeRefreshLayout;
private ListView list_view;
private SwipeAdapter adapter;
private List<Item> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_item);
list_view = (ListView) findViewById(R.id.lvDisplay);
itemList = new ArrayList<>();
adapter = new SwipeAdapter(this, itemList);
list_view.setAdapter(adapter);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
fetchItems();
}
});
}
#Override
public void onRefresh() {
fetchItems();
}
public void fetchItems() {
swipeRefreshLayout.setRefreshing(true);
DatabaseOperations db_op_sw = new DatabaseOperations(this);
SQLiteDatabase db = db_op_sw.getReadableDatabase();
Cursor display_cursor_swipe = db_op_sw.displaySwipeInfo(db);
String name;
int id, qty, price;
int offSet = 0;
if (display_cursor_swipe.moveToFirst()) {
do {
id = display_cursor_swipe.getInt(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.ID));
name = display_cursor_swipe.getString(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.NAME));
qty = display_cursor_swipe.getInt(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.QTY));
price = display_cursor_swipe.getInt(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.PRICE));
Item item = new Item(id, name, qty, price);
itemList.add(item);
offSet = offSet + id;
} while (display_cursor_swipe.moveToNext());
adapter.notifyDataSetChanged();
}
swipeRefreshLayout.setRefreshing(false);
}
}
DatabaseOperations.java
public class DatabaseOperations extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "item_info.db";
private static final String CREATE_QUERY = "create table " + ItemContract.ItemEntry.TABLE_NAME +
"(" + ItemContract.ItemEntry.ID + " text,"
+ ItemContract.ItemEntry.NAME + " text,"
+ ItemContract.ItemEntry.QTY + " integer,"
+ ItemContract.ItemEntry.PRICE + " integer);";
public DatabaseOperations(Context context) {
super(context, DB_NAME, null, DB_VERSION);
Log.d("Database Operations", "Database successfully created");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Table successfully created");
}
public Cursor displaySwipeInfo(SQLiteDatabase db) {
String[] projections = {ItemContract.ItemEntry.ID, ItemContract.ItemEntry.NAME,
ItemContract.ItemEntry.QTY, ItemContract.ItemEntry.PRICE};
Cursor display_cursor_swipe = db.query(ItemContract.ItemEntry.TABLE_NAME, projections, null, null, null, null, null, null, "2");
Log.d("Database Operations", "Viewed row");
return display_cursor_swipe;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
You are on the right track :)
So the 2 is the limit which is set on the query. You can also set offset,query in that place. You can keep a counter for refresh count and use it to create the offset.
Cursor display_cursor_swipe = db.query(ItemContract.ItemEntry.TABLE_NAME, projections, null, null, null, null, null, null, offset+",2"); //offset,limit
or
Cursor display_cursor_swipe = db.query(ItemContract.ItemEntry.TABLE_NAME, projections, null, null, null, null, null, null, "limit "+2+",offset "+offset);// limit 2 offset 3
or
you could resort to db.rawQuery(SQLSTATEMENT); // SQLSTATEMENT is select statement in string which has LIMIT,OFFSET set on it.

Trying to make Android database for the first time using SQLite, my app keeps crashing [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
Ive been trying to create a simplistic database on Android that has a table that gets three values,one for id, one for event desc. and the other for time which is on string format. problem is that it crashes for no reason and i cant find why. here is MainActivity:
public class MainActivity extends ListActivity {
private static final int MENU_EDIT = Menu.FIRST+1;
private static final int MENU_REMOVE = Menu.FIRST+2;
ArrayList <String> Events = new ArrayList<String>();
ArrayList <Integer> ids = new ArrayList<Integer>();
ListView lview = (ListView)findViewById(R.id.listview);
DBHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// registerForContextMenu(getListView());
db = new DBHandler(this);
// db.addInfo(new Day_Info("stef", "123"));
loadList();
}
private void loadList() {
try{
Events.clear();
ids.clear();
for(Day_Info e:db.getAllInfo()){
Events.add(e.getEvents()+", "+e.getTime());
ids.add(e.getId());
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2,Events);
lview.setAdapter(adapter);
}
catch(Exception e){
Toast.makeText(this, "Problem Loading List", Toast.LENGTH_LONG).show();
}
}
AND HERE is my database class:
class DBHandler extends SQLiteOpenHelper {
private static final String TABLE_NAME = "INFO";
private static final String DATABASE_NAME = "Schedule";
private static final String EVENT_DB ="event";
private static final String TIME_DB = "time";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
//Log.d("Database", "Database created");
}
#Override
public void onCreate(SQLiteDatabase db) {
String TABLE_CREATION = "CREATE TABLE "+ TABLE_NAME +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, EVENT TEXT not null,TIME TEXT not null)";
db.execSQL(TABLE_CREATION);
Log.d("Database", "Tables created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
void addInfo(Day_Info info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(EVENT_DB, info.getEvents());
cv.put(TIME_DB, info.getTime());
db.insert(TABLE_NAME, null, cv);
db.close();
}
public ArrayList<Day_Info> getAllInfo(){
ArrayList<Day_Info> List = new ArrayList<Day_Info>();
String selectQuery = "SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Day_Info info= new Day_Info();
info.setId(Integer.parseInt(cursor.getString(0)));
info.setEvents(cursor.getString(1));
info.setTime(cursor.getString(2));
List.add(info);
}while(cursor.moveToNext());
cursor.close();
}
return List;
}
}
Your coloumn at position 0 is an integer type
`_id INTEGER PRIMARY KEY AUTOINCREMENT`
But you are trying to fetch it as string
info.setId(Integer.parseInt(cursor.getString(0)));
instead use
info.setId(cursor.getInt(0));
Without logcat, i think this is the error you are facing. if you show your logs i will help more to determine the issue
you also declare _id as integer on need to convert cursor position (0) into integer put cursor.getInt(0)

Android Sqlite shows no such table

i want to add some image uri's to the Database. my Database table has two columns id and String Uri. The Problem is it shows No such table exist when trying to insert some Uris to Table. Here is my Code of Database Adapter Class.
package com.example.mystorage;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
// for customer registration
static final String KEY_ID = "id";
static final String KEY_URI = "uri";
static final String DATABASE_NAME = "IMAGE_DB";
static final String DATABASE_TABLE = "temp_images1";
static final int DATABASE_VERSION = 2;
static final String DATABASE_CREATE = "create table temp_images1 (id integer autoincrement, "
+ "uri text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS temp_images1");
onCreate(db);
}
}
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
// //////////////////////////////////////for
// customerRegistration////////////////
// customer registration for retrieve data
public Cursor getAllImages() {
return db.query(DATABASE_TABLE, new String[] {KEY_URI}, null,
null, null, null, null);
}
public Cursor getContentimage(long id) throws SQLException {
Cursor c = db.query(true, DATABASE_TABLE,
new String[] { KEY_ID, KEY_URI },
KEY_ID + "=" + id, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// customer registration for update data
public boolean updateimages(long id, String uri) {
ContentValues args = new ContentValues();
// args.put(KEY_ID,id);
args.put(KEY_URI, uri);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + id, null) > 0;
}
// customer registration for insert data
public long insertImages(String uri) {
ContentValues args = new ContentValues();
//args.put(KEY_ID, id);
args.put(KEY_URI, uri);
long n = db.insert(DATABASE_TABLE, null, args);
//db.insertOrThrow(DATABASE_TABLE, null, args);
return n;
}
// customer registration for remove data
public boolean deleteImages(long id) {
return db.delete(DATABASE_TABLE, KEY_ID + "=" + id, null) > 0;
}
}
here is My ImageAdapter class where i am calling the insert method.
mThumbs is uri Arraylist to Store the Content of Database While Retrieving.
public ImageAdapter(Context c, android.net.Uri uri) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
db.insertImages(uri.toString());
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
public ImageAdapter(Context c, ArrayList<Uri> imageUris) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
for (int i = 0; i < imageUris.size(); i++){
db.insertImages(imageUris.get(i).toString());
}
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
private void upadteAllImages() {
mTHumbs.clear();
try{
db.open();
Cursor c = db.getAllImages();
if (c.moveToFirst()) {
while (c.moveToNext()){
String uri = c.getString(1);
mTHumbs.add(Uri.parse(uri));
}
}
//mTHumbs.add((Uri) db.getAllImages());
db.close();
}catch(Exception e){
e.printStackTrace();
}
}
String query = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_URI + " TEXT not null "+)";
Fix the syntax error in your CREATE TABLE. AUTOINCREMENT can only be used with INTEGER PRIMARY KEY and you're missing the PRIMARY KEY.
Remove the try-catch in your onCreate() so that you get an exception in case of a syntax problem.
Uninstall your app so that the old database is removed and your helper onCreate() gets run again with the fixed SQL.
Some minor changes are required to create a table in database.
Please see this-
" CREATE TABLE temp_images1 ( id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "uri TEXT NOT NULL ) ; ";

Deleting SQLite record through Context Menu's onContextItemSelected() method

I'm building a note taking app in Android. I have developed insertion of the note in the app right now which I have done through SQLite database. Now I want to delete the particular note from the SQLite database through the context menu. When user long presses any record in the app it will through a context menu with "Delete" option. Now, My problem is I'm able to remove item from listview but it's not getting deleted from database.
Here's my code:
MainActivity.java:
#Override
public boolean onContextItemSelected(MenuItem item) {
int position;
super.onContextItemSelected(item);
if(item.getTitle().equals("Delete")) {
//Add code
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
position = (int)info.id;
//Notes note_id = (Notes)adapter.getNote(info.position);
db.deleteNote(new Notes(position));
list.remove(position);
this.adapter.notifyDataSetChanged();
}
return true;
};
DatabaseHandler.java:
package com.amitmerchant.notesapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notesManager";
private static final String TABLE_NOTES = "notes";
private static final String KEY_ID = "_id";
private static final String KEY_NOTE = "note";
private static final String KEY_DATE = "date_added";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_NOTES_TABLE = "CREATE TABLE "+TABLE_NOTES+"("+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+KEY_NOTE+" TEXT,"+KEY_DATE+" DATE"+")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote()); // Contact Name
// Inserting Row
db.insert(TABLE_NOTES, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Notes getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID,
KEY_NOTE, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Notes note = new Notes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return note;
}
// Getting All Contacts
public List<Notes> getAllNotes() {
List<Notes> noteList = new ArrayList<Notes>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Notes note = new Notes();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setNote(cursor.getString(1));
// Adding contact to list
noteList.add(note);
} while (cursor.moveToNext());
}
// return contact list
return noteList;
}
// Getting contacts Count
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote());
// updating row
return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
}
// Deleting single contact
public void deleteNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
db.close();
}
}
Notes.java
package com.amitmerchant.notesapp;
public class Notes {
// private variables
int _id;
String _note;
String _note_date;
// Empty constructor
public Notes() {
}
public Notes(int id, String _note) {
this._id = id;
this._note = _note;
}
public Notes(String _note) {
this._note = _note;
}
public Notes(int id) {
this._id = id;
}
public int getId() {
return this._id;
}
public void setId(int id) {
this._id = id;
}
public String getNote() {
return this._note;
}
public void setNote(String note) {
this._note = note;
}
}
Guys, what am I doing wrong here? Please correct me. Thanks!

problem in database in android

hi i am an SEO and i am in currently practicing android development of my own. i studied about database storing in android developers site and found an example code that to be in a notepad.
I tried using it in my project. In my project i have placed 2 edit boxes with a OK button, when the OK button is clicked the data in the edit box gets stored and it is shown in a new page.
the following is the code of my project's main class file,
{
b = (Button)findViewById(R.id.widget30);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(NotesDbAdapter.KEY_ET1);
String body = extras.getString(NotesDbAdapter.KEY_ET2);
mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (title != null) {
et1.setText(title);
}
if (body != null) {
et2.setText(body);
}
}
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(et1.getText().toString().length() == 0 && et2.getText().toString().length() == 0)
{
et.setVisibility(View.VISIBLE);
alertbox();
}
else
{
main.this.finish();
Intent myIntent = new Intent(v.getContext(), T.class);
startActivityForResult(myIntent, 0);
}
}
});
}
public void alertbox()
{
et = new TextView(this);
Builder alert =new AlertDialog.Builder(main.this);
alert.setTitle("Alert");
alert.setMessage("Required all fields");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
}
});
AlertDialog alert1 = alert.create();
alert1.show();
}
}
the following is the code of the DataBaseAdapter
public class NotesDbAdapter {
public static final String KEY_ET1 = "a";
public static final String KEY_ET2 = "b";
public static final String KEY_ROWID = "_id";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(String a, String b) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ET1, a);
initialValues.put(KEY_ET2, b);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_ET1,
KEY_ET2}, null, null, null, null, null);
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_ET1, KEY_ET2}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String a, String b) {
ContentValues args = new ContentValues();
args.put(KEY_ET1, a);
args.put(KEY_ET2, b);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
when i run the project the new page is opening but the data's entered is not shown there.
what is to be the error. pls teach me
You are going to need to get an instance of your database adapter
NotesDbAdapter adapter = new NotesDbAdapter(this); //pass activity context as a param
then you need to use the open method of the new database object to open the database
adapter.open();
now call the store method
String str = myEditText.getText().toString();
String str1 = "random other string";
adapter.createNote(str, str1);
I notice that your createNote method takes two params. I dont know where you want to get the other data from, so I just used 'random other string'. Sub in the data you want to store as appropriate.
Finally you will need to close the database:
adapter.close();
And you have successfully stored the information. See this for help on how to use the console to view the data that you have entered into the database. (See specifically the sqlite3 portion of the page) Alternatively you could write some code to display it on the screen after retrieving it. You are going to need to read about cursors if you want to retrieve info. See here for some information on that.

Categories

Resources