I'm trying to insert a row in a sqlite database's table, but when I call the insertOrThrow() method (Class Sqlitedatabase) i get this exception:
"Application did not close the cursor or database object that was opened here"
I don't understand why:
here's the code for the main class:
........
ContentValues values = new ContentValues();
values.put("nome", info.getString("nome"));
values.put("ingredienti", info.getJSONObject("ingredienti").toString());
values.put("descrizione", info.getString("descrizione"));
values.put("persone", info.getString("persone"));
values.put("tempo", info.getString("tempo"));
values.put("facilita", info.getString("facilita"));
if(info.getString("url_foto")!="/images/ricettapredefinita.jpg")
values.put("foto", true);
else
values.put("foto", false);
values.put("categoria", info.getString("categoria"));
values.put("zona", info.getString("regione"));
values.put("ethnos", info.getString("etnica"));
values.put("voto", info.getString("voto"));
// Open database
DbAdapter mDbHelper = new DbAdapter(Main.this);
mDbHelper.open_w();
long ritorno=mDbHelper.createRecipe(values);
These are the main methods for DbAdapter Class:
private static final String DATABASE_CREATE =
"CREATE TABLE recipes (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"nome VARCHAR(255) NOT NULL," +
"ingredienti TEXT NOT NULL," +
"descrizione TEXT " +
"persone SMALLINT," +
"tempo TINYINT(3)," +
"facilita SMALLINT," +
"foto BOOL," +
"voto TINYINT(3)," +
"categoria VARCHAR(255)," +
"zona VARCHAR(255)," +
"ethnos VARCHAR(255));";
public long createRecipe(ContentValues info) {
return mDb.insertOrThrow(DATABASE_TABLE, null, info);
}
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 DbAdapter open_w() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
Anyone has an idea for what the problem could be?
You should add mDbHelper.close() at end.
you have to add a mDbHelper.close(); when you are sure that I do not need more a mDbHelper.
I have solved same issue by doing this. I hope is working for u.
Related
#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
EditText USER_NAME, USER_PASS, CON_PASS, USER_EMAIL;
String user_name, user_pass, con_pass, user_email;
Button REG;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
USER_NAME = (EditText) findViewById(R.id.reg_user);
USER_PASS = (EditText) findViewById(R.id.reg_pass);
CON_PASS = (EditText) findViewById(R.id.con_pass);
USER_EMAIL = (EditText) findViewById(R.id.reg_email);
REG = (Button) findViewById(R.id.user_reg);
REG.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
user_name = USER_NAME.getText().toString();
user_pass = USER_PASS.getText().toString();
con_pass = CON_PASS.getText().toString();
user_email = USER_EMAIL.getText().toString();
if (!(user_pass.equals(con_pass))) {
Toast.makeText(getBaseContext(), "Password are not matching", Toast.LENGTH_LONG).show();
USER_NAME.setText("");
USER_PASS.setText("");
CON_PASS.setText("");
USER_EMAIL.setText("");
} else {
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, user_name, user_pass, user_email);
Toast.makeText(getBaseContext(), "Registration is suessful", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
}
It is because you are creating table each time you insert a row. To solve this problem you need to change the create table query "CREATE TABLE 'TABLE_NAME' IF NOT EXISTS". The "IF NOT EXISTS" will restrict the system to create the database again if it is created once.
You are calling creating a new Table every time, you create an instance of DatabaseOperations - as your SQL statement 'CREATES'
Modify SQL_CREATE_ENTRIES to something like below
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + + " integer primary key autoincrement, "+
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
Edit
1) I've update query to include auto-increment your primary key
2) In your onUpgrade method add the line
db.execSQL("DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME);
This will delete the table when you change the version of DB.
Next, update the version of by 1, to 3.
Re-run app, it will be rebuild the DB table.
I am working on android application which stores some data in database when the user starts the application it fetches data from the database to an ArrayList and keeps that ArrayList throughout the application life cycle. whenever I require an update to data I updates both database and ArrayList which holds the data, this approach reduces the CPU effort. here I have to update the database via a non ui thread, so that I need some suggestions,
1- is this a good approach ?
2- I have a database helper class which directly interacts with the database, and I am maintaining separate class for each tables, that communicates with the UI and Database helper class, so where should I implement thread , either in the Helper class or in the table corresponding class ?
code
DbHandler
#Override
public void onCreate(SQLiteDatabase db) {
FirstTable.createDatabaseTable(db);
SecondTable.createDatabaseTable(db);
}
public void insertData(String tableName, ContentValues contentValues) {
SQLiteDatabase db = getWritableDatabase();
db.insert(tableName, null, contentValues);
dbClose();
}
public Cursor readData(String tableName, String[] columns, String selection, String[]
selectionArgs, String groupBy, String having, String orderBy, String limit) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
return cursor;
}
public void deleteData(String tableName, String id, NewsItem newsItem) {
SQLiteDatabase db = getWritableDatabase();
db.delete(tableName, id + " =?", new String[]{String.valueOf(newsItem.getmGuid())});
dbClose();
}
public void updateData(String tableName, ContentValues contentValues, String where, String[] whereArgs) {
SQLiteDatabase db = getWritableDatabase();
db.update(tableName, contentValues, where, whereArgs);
dbClose();
}
public void dbClose() {
if (mDbHandler != null) {
mDbHandler.close();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
FirstTable.deleteTable(db);
SecondTable.deleteTable(db);
onCreate(db);
}
Table Specific class
public static void createDatabaseTable(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
public static void deleteTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void createData(Data data) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_TITLE, data.getTitle());
contentValues.put(COLUMN_LINK, data.getLink());
DbHandler dbHandler = DbHandler.getInstance(mContext);
dbHandler.insertData(TABLE_NAME, contentValues);
}
public ArrayList<NewsItem> readData() {
ArrayList<Data> allData = new ArrayList<>();
DbHandler dbHandler = DbHandler.getInstance(mContext);
Cursor cursor = dbHandler.readData(TABLE_NAME, null, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Data data = new Data();
data.setTitle(cursor.getString(2));
data.setLink(cursor.getString(3));
allNewsList.add(newsItem);
} while (cursor.moveToNext());
}
return allData;
}
public void deleteData(Data data) {
DbHandler dbHandler = DbHandler.getInstance(mContext);
dbHandler.deleteData(TABLE_NAME, ID, data);
}
suggest me good method
Yes its good idea to store data and maintain in background process. I like to suggest you that to make a common class to handle Database & Tables.
For example
public class DatabaseHandler extends SQLiteOpenHelper{
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "demo_database";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
private static final String TABLE_PROINFO = "proinfo";
private static final String TABLE_RETAPROINFO = "retaproinfo";
private static final String TABLE_ATTENDANCE = "attendance";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_STUDID = "studid";
private static final String KEY_AVAILABILITY = "availability";
private final ArrayList<Bean_attendance> att_list = new ArrayList<Bean_attendance>();
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
SQLiteDatabase db;
Cursor cursor;
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORY_NAME_TABLE = "CREATE TABLE " + TABLE_ATTENDANCE
+ "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_STUDID + " TEXT,"
+ KEY_AVAILABILITY + " TEXT" + ")";
db.execSQL(CREATE_CATEGORY_NAME_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
int upgradeTo = oldVersion + 1;
while (upgradeTo <= newVersion) {
switch (upgradeTo) {
case 1:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 2:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 3:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 4:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 5:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 6:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 7:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 8:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 9:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 10:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 11:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 12:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
}
upgradeTo++;
}
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
public void Add_Attandance(Bean_attendance contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STUDID, contact.getStud_id());
values.put(KEY_AVAILABILITY, contact.getAvailability());
// Inserting Row
db.insert(TABLE_ATTENDANCE, null, values);
db.close(); // Closing database connection
}
public ArrayList<Bean_attendance> Get_Attandance() {
try {
att_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ATTENDANCE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bean_attendance contact = new Bean_attendance();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setStud_id(cursor.getString(1));
contact.setAvailability(cursor.getString(2));
// Adding contact to list
att_list.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return att_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_attandance", "" + e);
}
return att_list;
}
public int Update_MainAttandnce(String availble,int id) {
String countQuery = "UPDATE " + TABLE_ATTENDANCE + " SET " + KEY_AVAILABILITY
+ " = " + "\"" + availble + "\"" + " where " + KEY_ID + "=" + "\"" + id
+ "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
public void Delete_Attandance_main(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ATTENDANCE, KEY_ID + "=" + id, null);
db.close();
}
public void Attandanceremove() {
SQLiteDatabase db = this.getWritableDatabase();
// context.deleteDatabase(DATABASE_NAME);
db.execSQL("delete from " + TABLE_ATTENDANCE);
// db.delete(DATABASE_TABLE, null, null);
}
}
I'm developing a program using database.
I'm stuck on inserting the data typed from EditText, keep on getting NullPointerException.
Here is my code:
AddBusDataActivity.java
public class AddBusDataActivity extends ActionBarActivity {
SQLiteDatabase mBusDatabse;
BusDatabaseHelper mBusDatabaseHelper;
EditText mNumber;
EditText mDestination;
EditText mArrivalTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
mBusDatabaseHelper = new BusDatabaseHelper(AddBusDataActivity.this, Constants.DATABASE_NAME, null, Constants.VERSION);
mNumber = (EditText)findViewById(R.id.number_text);
mDestination = (EditText)findViewById(R.id.destination_text);
mArrivalTime = (EditText)findViewById(R.id.arrival_time);
}
public void addBusActivityButton(View view) {
mBusDatabse = mBusDatabaseHelper.getWritableDatabase();
BusData bus = new BusData(mNumber.getText().toString(), mDestination.getText().toString(), Integer.valueOf(mArrivalTime.getText().toString()));
mBusDatabaseHelper.addBusData(bus); // error here
mBusDatabaseHelper.close();
Toast.makeText(AddBusDataActivity.this, "Bus data successfully added", Toast.LENGTH_SHORT).show();
this.finish();
}
}
BusDatabaseHelper.java
public class BusDatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase mBusDatabase;
public BusDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+ Constants.TABLE_NAME + " (" + Constants.KEY_ID + " integer primary key autoincrement, " +
Constants.NUMBER + " text not null, " + Constants.DESTINATION + " text not null, " + Constants.ARRIVAL_TIME + " integer not null);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table " + Constants.TABLE_NAME + ";");
onCreate(db);
}
public void addBusData(BusData busData) {
ContentValues busValues = new ContentValues();
busValues.put(Constants.NUMBER, busData.getmNumber());
busValues.put(Constants.DESTINATION, busData.getmDestination());
busValues.put(Constants.ARRIVAL_TIME, busData.getmArrivalTime());
mBusDatabase.insert(Constants.TABLE_NAME, null, busValues); // error here
}
}
Error message
Caused by: java.lang.NullPointerException
at com.id11201478.exercise6.BusDatabaseHelper.addBusData(BusDatabaseHelper.java:36)
at com.id11201478.exercise6.AddBusDataActivity.addBusActivityButton(AddBusDataActivity.java:36)
I have separate Constants.java class for storing thoses values.
Thanks in advance!
It looks like mBusDatabase in BusDatabaseHelper is never initialised and therefore is null. Dereferencing it on line 36 causes your NPE.
You don't actually need it if you modify addBusData to grab it each time:
public void addBusData(BusData busData) {
ContentValues busValues = new ContentValues();
busValues.put(Constants.NUMBER, busData.getmNumber());
busValues.put(Constants.DESTINATION, busData.getmDestination());
busValues.put(Constants.ARRIVAL_TIME, busData.getmArrivalTime());
getWritableDatabase().insert(Constants.TABLE_NAME, null, busValues);
}
The variable
BusDatabaseHelper.mBusDatabase
is null. You need to initialize it!
Otherwise how does the system knows what mBusDatabase is
try to add this before insert
mBusDatabase= this.getWritableDatabase();
There is a problem with insetion in database. I don't know what to do.
It writes error inserting.
public class MainActivity extends Activity implements OnClickListener {
BaseOpener bo;
private static final String ML = "ML";
Button read, write;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
read = (Button) findViewById(R.id.read);
read.setOnClickListener(this);
write = (Button) findViewById(R.id.write);
write.setOnClickListener(this);
bo = new BaseOpener(this);
Log.i("Ml", "good start");
}
#Override
public void onClick(View v) {
SQLiteDatabase db = bo.getWritableDatabase();
switch (v.getId()) {
case R.id.write:
{
ContentValues cv = new ContentValues();
Log.i("ML", "write");
cv.put("id", 1);
cv.put("name", "Petr");
cv.put("phone", "911");
cv.clear();
db.insert("table1", null, cv);
}
break;
case R.id.read:
{`enter code here`
Log.i("ML", "read");
Cursor c = db.query("table1",null,null,null,null,null,null);
if(c.moveToFirst()){
int idColIndex = c.getColumnIndex("id");
int nameColIndex = c.getColumnIndex("name");
int emailColIndex = c.getColumnIndex("phone");
Log.i("ML",
"ID = " + c.getInt(idColIndex) +
", name = " + c.getString(nameColIndex) +
", phone = " + c.getString(emailColIndex));
}
}
break;
}
db.close();
Log.i("ML", "the base is closed");
}
}
public class BaseOpener extends SQLiteOpenHelper {
public BaseOpener(Context context) {
super(context, "contacts", null, 1);
Log.i("ML", "the base is ready");
}`enter code here`
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table table1 (" + "id integer primary key,"
+ "name String," + "phone String" + ");");
Log.i("ML", "table1 is ready");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
clear()
Removes all values. Read more on ContentValues here
Your table lists id as primary key so you can't insert it twice. I would just comment out the cv.put("id",1) line and let sqlite handle it.
//cv.put("id", 1);
db.execSQL("create table table1 (" + "id integer primary key,"
+ "name String," + "phone String" + ");");
Log.i("ML", "table1 is ready");
Also from your next app on consider naming your id column _id. This will make the table more compatible with cursor adapters and such.
Look at these links they all use _id
cursorAdapter ContentProvider ListView
I built an app that so far manages to ADD text to a database (cannot verify yet but I killed the FC). However, when I try to read from the database it FCs because I'm unsure of how to use the Cursor object. I read the documentation and it confuses me more. I have a database with table "records" and a single column "texts". While my project manages to input text into the database (via an EditText), I'm trying unsuccessfully to return all the database entries from this "texts" column into a textView.
DB Helper inner-class:
private class dbHelper extends SQLiteOpenHelper {
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
System.out.println("create statement"+SQL_CREATE_ENTRIES);
try
{
db.execSQL(SQL_CREATE_ENTRIES);
}catch(SQLiteException sql)
{
sql.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS records");
onCreate(db);
}
public void addRecord(String t) {
ContentValues values = new ContentValues(1);
values.put(RECORDS_COLUMN_TEXTS,t);
getWritableDatabase().insert(TABLE_NAME, RECORDS_COLUMN_TEXTS, values);
}
public Cursor getRecords() {
return getWritableDatabase().rawQuery("select * from " + TABLE_NAME, null);
}
}
Within main class:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "CSCI598";
private static final String TABLE_NAME = "records";
public static final String RECORDS_COLUMN_TEXTS = "texts";
private dbHelper openHelper;
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
public void onClick(View v) {
TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);
openHelper = new dbHelper(this);
switch(v.getId()) {
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
cursor.moveToFirst();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString());
break;
case R.id.append1:
String txt=et.getText().toString();
openHelper.addRecord(txt);
break;
}
logcat: http://pastebin.com/mqUn6g7P
As you can see, I'm probably trying something very stupid with the action for clicking the fetch button, ie. "openHelper.getRecords().toString()" attempting to convert all that Cursor returns to string. How can I go about this alternately in the simplest fashion?
Ok First you have get the strings from the Cursor by doing this
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
Then you can set it to the textView
tv.setText(sb.toString);
This should work actually
.Replace this part of your code
case R.id.fetch1:
tv.setText(openHelper.getRecords().toString());
break;
With this
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString);
break;
Also remove autoincrement for Text when you create the table
Replace this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
With this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT" + ")";
Also Add table name in the constructor instead of database name. Change this:
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
To this:
public dbHelper(Context context) {
super(context, TABLE_NAME, null, DATABASE_VERSION);
}