what i am trying do is create a table then insert some values into it then and select.
The problem i am facing is the app is unfortunately stopping.I don't know what is the problem.
My code is:
This class calls the database handler
public class SaveEvents extends Activity {
private static final String DB_NAME = "EventDB";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
Bundle extras=getIntent().getExtras();
String event=extras.getString("event");
String date=extras.getString("date");
String college=extras.getString("college");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.insert_data(event,date,college);
String c=db.select_data();
Toast.makeText(getApplicationContext(), "EventName: "+c+"", Toast.LENGTH_LONG).show();
}
}
Database Handler
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "EventDB";
private static final String TABLE_NAME = "eventlist";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_ITEM_TABLE;
CREATE_ITEM_TABLE = "CREATE TABLE eventlist(eventname varchar(100),eventdate varchar(100),college varchar(100));";
db.execSQL(CREATE_ITEM_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
void insert_data(String eventname,String date,String college)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("eventname", eventname);
values.put("eventdate",date);
values.put("college",college);
db.insert(TABLE_NAME,null,values);
db.close();
}
public String select_data()
{
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT eventname FROM eventlist where eventname='techcontest'";
String c=null;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
c=cursor.getString(0);
return c;
}
}
My logcat shows
03-16 20:00:19.116 8378-8378/com.example.android E/SQLiteLog﹕ (1) no such table: eventlist
03-16 20:00:19.122 8378-8378/com.example.android E/SQLiteDatabase﹕ Error inserting college=acs university eventdate=2-02-15 eventname=techocontest
android.database.sqlite.SQLiteException: no such table: eventlist (code 1): , while compiling: INSERT INTO eventlist(college,eventdate,eventname) VALUES (?,?,?)
It doesn't look like you are closing the database in the select_data() method.
Related
Hello I want to implement a simple survey. I successfully added the questions with an insert query. The Questions however get added every time when I run the application.
I tried to use "Drop table if exists" but nothing happens.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME= "Questionpool.db";
public static final String createdb = "Create table dtaquestions( questionId Integer Primary Key Autoincrement, dtaQuestion Varchar(100), dtaDepartment Varchar(100))";
public static final String dropdb = "Drop table if exists dtaquestions";
Context context;
public DatabaseHelper(Context context) {
super(context, DBNAME , null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createdb);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(dropdb);
}
And in the Survey class I have this,
myDb = new DatabaseHelper(this);
SQLiteDatabase DB2=myDb.getWritableDatabase();
insertQuestions(DB2);
final Cursor res = getAllData(DB2);
bViewAll = (Button) findViewById(R.id.bViewAll);
bViewAll.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
if(res.getCount()== 0){
tv.setText("nooo");
}else{
int counter = 0;
while(res.moveToNext()){
//show on screen
}
}
}
});
public void insertQuestions(SQLiteDatabase db){
String [] dtaQuestions = fillArray();
String [] dtaQuestionsDep = fillDepartment();
for (int i = 0 ; i < 18 ; i++ ){
ContentValues cv = new ContentValues();
cv.put("dtaQuestion", dtaQuestions[i]);
cv.put("dtaDepartment", dtaQuestionsDep[i]);
db.insert("dtaquestions", null, cv);
}
}
public Cursor getAllData(SQLiteDatabase db){
Cursor res = db.rawQuery("Select * from dtaquestions", null);
return res;
}
I have no idea why the drop query isn't working and the query keeps repeating itself.
Read de cocumentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.
When you create the helper the version is always 1.
super(context, DBNAME , null, 1);
You need to change the version.
You can declare the version and then use it:
private static final int VERSION=2;
public DatabaseHelper(Context context) {
super(context, DBNAME , null,VERSION);
this.context = context;
}
i'm trying to make simple signup/login app which uses SQLite database, so far i got this code. This is my "registration" activity which should implement users name and pin(password) to database after pushing register button i guess, sadly the app crashes.
EditText reName, rePin;
Button reRegister;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
reName = (EditText)findViewById(R.id.reName);
rePin = (EditText)findViewById(R.id.rePin);
reRegister = (Button)findViewById(R.id.reRegister);
reRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Imie = reName.getText().toString();
String Haslo = rePin.getText().toString();
Contacts c =new Contacts();
c.setName(Imie);
c.setPass(Haslo);
helper.insertContacts(c);
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
}
});
}
Here's also my DatabaseHelper code, i guess that the problem is somewhere in this code, but i cant really find it. What should i do or where should i find solution for this? :)
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"name text not null, pass text not null);";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertContacts(Contacts c){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select + from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String name) {
db = this.getReadableDatabase();
String query = "select * from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a,b;
b = "not found";
if (cursor.moveToFirst()){
do {
a =cursor.getString(2);
if (a.equals(name)){
b= cursor.getString(3);
break;
}
}
while (cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
#edit - Logcat errors
12-16 13:08:14.316 3541-3541/com.example.mateusz.sqllogowanie E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mateusz.sqllogowanie, PID: 3541
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
at com.example.mateusz.sqllogowanie.DatabaseHelper.onCreate(DatabaseHelper.java:36)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:333)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:238)
at com.example.mateusz.sqllogowanie.DatabaseHelper.insertContacts(DatabaseHelper.java:42)
at com.example.mateusz.sqllogowanie.SignUp$1.onClick(SignUp.java:36)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Your SqliteDatabase object is null.
Change this:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
db.execSQL(TABLE_CREATE); //db is null here
this.db = db;
}
to:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
this.db = sqLiteDatabase;
db.execSQL(TABLE_CREATE);
}
Also for in your insertContacts() method change query to:
String query = "select * from contacts";
Just look into you query string insertContacts you are using + instead of *
just change query to
String query = "select * from contacts";
I just implemented an SQLite database for a simple to do app for persistence. However, the problem is that when I restart the app, I do not have my data that is stored in an SQLite database. The following is my SQLite helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final String TABLE_NAME = "student";
public static final String ID = "id";
public static final String TO_DO = "todo";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TO_DO_TABLE = "CREATE TABLE "
+ TABLE_NAME
+ "("
+ ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TO_DO
+ " TEXT"
+ ")";
sqLiteDatabase.execSQL(CREATE_TO_DO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String todo){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
return true;
}
}
And in my MainActivity.java, I'm adding my List items into the database as well as the ListView.
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
private final int REQUEST_CODE = 10;
ArrayList <String> toDoItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ListView listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = (ListView) findViewById(R.id.listViewItems);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, toDoItems);
listItems.setAdapter(adapter);
databaseHelper = new DatabaseHelper(this);
...
}
public void addItem(View v){
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
String item = newItem.getText().toString();
databaseHelper.insertData(item);
adapter.add(item);
newItem.setText("");
}
}
I believe I need to do something in the onCreate method but my addItem(View v) method is called through the button onClick.
as #cristian_franco said, the toDoItems is empty yet. What you need to do is to create another method in DatabaseHelper class like this.
public ArrayList<String> showStudents(){
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0)+" "+cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
and then assign toDoItems like this
databaseHelper = new DatabaseHelper(this);
toDoItems=databaseHelper.showStudents();
Let me know if there is any mistake in my code.
implment this function for get the values,
public void getDatos(){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from student",null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex("todo"));
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
cursor.moveToNext();
}
}
}
yout funciion for save is correct only you need get the information
I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}
I just recently started working on a project but my program repeatedly crashes. I think it is due to getWritableDatabase. I was following a tutorial and i did everything they told me to, i even checked over my code multiple times. If u are interested in the link to the tutorial, it is https://www.youtube.com/watch?v=38DOncHIazs
public class AddExpense extends Activity {
EditText inputDate , inputDescription, inputCategory, inputAmount;
Context context;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
inputDate = (EditText) findViewById(R.id.inputDate);
inputDescription = (EditText) findViewById(R.id.inputDescription);
inputCategory = (EditText) findViewById(R.id.inputCategory);
inputAmount = (EditText) findViewById(R.id.inputAmount);
}
public void AddExpense(View view){
String date = inputDate.getText().toString();
String description = inputDescription.getText().toString();
String category = inputCategory.getText().toString();
String amount = inputAmount.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformations(date, description, category, amount, sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data Saved", Toast.LENGTH_LONG).show();
userDbHelper.close();
}
}
And this is my database helper class
public class UserDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "EXPENSE.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE " + ExpenseDatabase.NewExpenseItem.TABLE_NAME + " ("+ ExpenseDatabase.NewExpenseItem.DATE+" TEXT,"+ ExpenseDatabase.NewExpenseItem.DESCRIPTION+ " TEXT,"+
ExpenseDatabase.NewExpenseItem.CATEGORY+" TEXT," + ExpenseDatabase.NewExpenseItem.AMOUNT+ " TEXT);";
public UserDbHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS", "Database created / opened");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created");
}
public void addInformations(String date, String description, String category, String amount,SQLiteDatabase db ){
ContentValues contentValues = new ContentValues();
contentValues.put(ExpenseDatabase.NewExpenseItem.DATE,date);
contentValues.put(ExpenseDatabase.NewExpenseItem.DESCRIPTION, description);
contentValues.put(ExpenseDatabase.NewExpenseItem.CATEGORY, category);
contentValues.put(ExpenseDatabase.NewExpenseItem.AMOUNT, amount);
db.insert(ExpenseDatabase.NewExpenseItem.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted in DB");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
In my experience it is better if you just make a method in your UserDbHelper class and pass the relevant values to that method.
Try to do everything related to database in that class itself. I think it will work.
EDIT:
public void addInformation(your values){
ContentValues values = new ContentValues();
values.put();
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE,null,values);
db.close();
}
Try using this userDbHelper = new UserDbHelper(this); some you're context is not initialized. It might be the issue