SQL table not found exception - android

i have made a table and its fields but i get error that no such row exist and if i comment them out then it is not detecting the table also showing no such table exist.Here's the code:
package com.example.ifest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper{
private static final String DB_NAME = "event_db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "_table";
private static final String EVENT_NAME = "_name" ;
private static final String EVENT_ID = "_no" ;
private static final String EVENT_TYPE = "_type" ;
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ EVENT_NAME + " TEXT NOT NULL, " + EVENT_TYPE + " TEXT NOT NULL);" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
and the code for my other acitvity is:
public class ProfileView extends ListActivity{
String e,e1;
static int p = 0;
Spinner spn ;
Button b1,b2;
EditText et;
String str1;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list.add("Create");
openDB();
p++;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(position == 0){
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition());
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
}
}
protected void addDB(String name,int id) {
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_name",name);
if(id == 0)
cv.put("type","WIFI");
else if(id == 1)
cv.put("type","BLUETOOTH");
else if(id == 2)
cv.put("type","MEDIA");
db.insert("_table", null , cv);
db.close();
}
private void openDB() {
if(p != 0){
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+ "event_db",null);
c.moveToFirst();
while(c.moveToNext()){
list.add(c.getString(1));
Log.d("cursor", c.getString(1));
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflate = getMenuInflater();
inflate.inflate(R.menu.string_main,menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition());
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
break;
case R.id.item2:
break;
case R.id.item3:
Intent i = new Intent("com.example.ifest.ABOUTUS");
startActivity(i);
break;
case R.id.item4:
finish();
break;
}
return true;
}
}

You are using "type" on your contentvalue but your column is named: "_type".

You are querying the event_db table which is the name of your database, not your table
Cursor c = db.rawQuery("SELECT * FROM "+ "event_db",null);
You should query the _table table
Cursor c = db.rawQuery("SELECT * FROM "+ "_table",null);
By the way it would be more clear if you name your database db (I doubt you need more than one db anyway) and your table _event (you can have many tables and you should name them accordingly to their role and not just _table)

Related

Can't save chosen item from spinner to database

I have problem with my database. I want to save selected item from spinner to sql database. The problem is,i don't know why, but i can't save chosen item from spinner to database. I was trying out this database with EditText and everything was fine.
MainActivity :
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
DatabaseHelper db;
Spinner spinner;
Button addData, showData;
TextView saveChosenItemFromSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
addData = (Button) findViewById(R.id.addDataBtn);
showData = (Button) findViewById(R.id.showDataBtn);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinnerDemo, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
saveChosenItemFromSpinner = (TextView) findViewById(R.id.text);
AddData();
// showData();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String text = adapterView.getItemAtPosition(i).toString();
saveChosenItemFromSpinner.setText(text);
// Toast.makeText(adapterView.getContext(), text, Toast.LENGTH_SHORT).show();
AddData();
}
public void AddData() {
addData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = db.insertData(saveChosenItemFromSpinner.getText().toString() );
if (isInserted)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
DatabaseHelper class :
public static final String DATABASE_NAME = "TrainingPlan.db";
public static final String TABLE_NAME = "Chest";
public static final String COL_1 = "ID";
public static final String COL_2 = "Upper_section";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,UpperSectionExercises TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String upperSectionExercisesString) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, upperSectionExercisesString);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else
return true;
}
}
I've tried to find solution on my own,but i find nothing. Can i have some tips?
You are using different key with content values than your column name.
use
contentValues.put("UpperSectionExercises", upperSectionExercisesString);
or change your create statement.
Your Table creation query is wrong. It will be like
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY
KEY AUTOINCREMENT, "+ COL_2+" TEXT)");

By long clicking on listview delete its contents from SQLite and listview that is clicked

Can anyone show me how to delete contents from an SQLite database and listview by long clicking on it? Also, do I have to delete only contents from SQLite database or from both SQLite database and listview?
Here are my project classes:
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "products.db";
private static final String TABLE_NAME = "products";
private static final String COLUMN_ID = "_id";
private static final String MARKET = "market";
private static final String PRODUCT = "product";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MARKET + " TEXT, "
+ PRODUCT + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
onCreate(db);
}
public Cursor getRecords() {
db = getReadableDatabase();
return db.rawQuery(
"SELECT * FROM " + TABLE_NAME,
null);
}
public void addRecords(String market, String product) {
db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MARKET, market);
contentValues.put(PRODUCT, product);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public void deleteRecords(int id){
}}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
DatabaseHelper databaseHelper;
ShoppingCartAdapter shoppingCartAdapter;
private static final int TIME_ENTRY_REQUEST_CODE = 1;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view_main);
databaseHelper = new DatabaseHelper(this);
ListView listView = (ListView) findViewById(R.id.list_view_main);
shoppingCartAdapter = new ShoppingCartAdapter(this, databaseHelper.getRecords(), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(shoppingCartAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, int position, long id) {
final int pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton("CANCEL", null);
builder.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_template, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_id) {
Intent intent = new Intent(this, AddContentActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String market = data.getStringExtra("market");
String product = data.getStringExtra("product");
databaseHelper.addRecords(market, product);
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
}
}
}
}
AddContentActivity
public class AddContentActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
}
public void onAddButton(View view){
Intent intent = getIntent();
EditText marketet = (EditText) findViewById(R.id.marketet_id);
EditText productet = (EditText) findViewById(R.id.productet_id);
intent.putExtra("market", marketet.getText().toString());
intent.putExtra("product", productet.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
ShoppingCartAdapter
public class ShoppingCartAdapter extends CursorAdapter{
public ShoppingCartAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView marketTv = (TextView) view.findViewById(R.id.markettv_id);
TextView productTv = (TextView) view.findViewById(R.id.producttv_id);
marketTv.setText(cursor.getString(1));
productTv.setText(cursor.getString(2));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_view_template, parent, false);
return view;
}
}
After couple of days I found solution on my question.If there is better way of doing delete, please post answer.
I added following lines of code:
Main Activity
Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
final int item_id = cursor.getInt(cursor.getColumnIndex("_id"));
databaseHelper.deleteRecords(item_id );
cursor.requery();
DatabaseHelper
public void deleteRecords(int id){
db.delete(TABLE_NAME, COLUMN_ID + "=" + id, null);
}
EDIT:
replaced cursor.requery(); with
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
because using requery(); is deprecated but both lines of code work.

How to read,add Database into ArrayList?

I'm new to Android Studio here. I don't know how to read and add database into Arraylist . Could you guys please help me with it :P ? I have already tried some methods, but It still didn't work #.# .
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "ToDoList.db";
public static final String TABLE_NAME = "ToDoList_Table";
public static final String DATABASE_TABLE = "ToDo_DBTable";
public static final String COL_1 = "ID";
public static final String COL_2 = "TODO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,TODO 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 TODO) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, TODO);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public ArrayList<String> getRecords(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> data=new ArrayList<String>();
Cursor cursor = db.query(TABLE_NAME, new String[]{COL_2},null, null, null, null, null);
String fieldToAdd=null;
while(cursor.moveToNext()){
fieldToAdd=cursor.getString(0);
data.add(fieldToAdd);
}
cursor.close();
return data;
}
}
public class MainActivity extends AppCompatActivity
{
DatabaseHelper TDdb;
ArrayList<String> todoItems;
ArrayAdapter<String> aTodoAdapter;
ListView lvItems;
EditText editTD;
Button btnAddItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
populateArrayItems();
editTD = (EditText) findViewById(R.id.tdEditText);
lvItems = (ListView) findViewById(R.id.lvItems);
btnAddItems = (Button) findViewById(R.id.tdAddItems);
AddData();
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.list_ingredients);
getSupportActionBar().setDisplayUseLogoEnabled(true);
lvItems.setAdapter(aTodoAdapter);
lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
long id) {
todoItems.remove(position);
aTodoAdapter.notifyDataSetChanged();
return true;
}
});
TDdb = new tdls.todolistapps.DatabaseHelper(this);
}
public void AddData()
{
btnAddItems.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean isInserted = TDdb.insertData(editTD.getText().toString());
if(isInserted = true )
Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Items not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
public void populateArrayItems()
{
todoItems = new ArrayList<String>();
todoItems.add("Item 1");
todoItems.add("Item 2");
todoItems.add("Item 3");
aTodoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.add("Email");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onAddItem(View v)
{
aTodoAdapter.add(editTD.getText().toString());
editTD.setText("");
}
}
Here is the picture, it said that Item Inserted but It won't display :'(
Try replacing following code
if(isInserted = true ){
todoItems.add(editTD.getText().toString());
aTodoAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this, "Items not Inserted", Toast.LENGTH_LONG).show();
}
As you need to update adapter as well after adding data to database.
At First change your getRecords() function like below:
public ArrayList<String> getRecords(){
open();
ArrayList<String> data = new ArrayList<>();
Cursor cursor = db.query(DATABASE_TABLE, new String[]{COL_2}, null, null, null, null, null, null);
if (cursor.moveToFirst()){
do {
data.add(cursor.getString(0));
} while (cursor.moveToNext());
}
close();
return data;
}

Deleting from SQL database android

I have a list view and when the user clicks a specific item a contextual action mode is displayed with only one item in it (that is supposed to delete it). However, when I click it, the database is not updated (the item is still on the list). Could anyone help me ?
In MainActivity:
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
protected Object mActionMode;
int catPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
List<String> all = entry.getAllCategory();
if(all.size()> 0){
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
}else{
Toast.makeText(MainActivity.this,"No items to display",Toast.LENGTH_LONG).show();
}
entry.close();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
catPos = position;
if (mActionMode != null) {
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = MainActivity.this
.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete_cat:
// shareCurrentItem();
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
entry.deleteCat(catPos);
List<String> all = entry.getAllCategory();
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
entry.close();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
in Actual Database:
public class CategoryDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";
private static final String DATABASE_NAME = "DBCategory";
private static final String DATABASE_TABLE = "categoryTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public CategoryDatabase(Context c){
ourContext = c;
}
public CategoryDatabase open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CATEGORY + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long createEntry(String category) {
ContentValues cv = new ContentValues();
cv.put(KEY_CATEGORY, category);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public List<String> getAllCategory() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + DATABASE_TABLE;
Cursor cursor = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
List.add(cursor.getString(1));
} while (cursor.moveToNext());
}
return List;
}
public void deleteCat(int catPos) {
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + catPos, null);
}
}
Deleting as "entry.deleteCat(catPos);" is not right. If You use Your catPos, which is the position inside the listView, it will not delete the entry from database. You made an INTEGER_PRIMARY_KEY_AUTOINCREMENT inside Your Database, so this Integer will generated automatically and can differ from Your position Integer. What You have to do is, to make a query method inside Your Database where You get even the ID from Your DB-Entry. Then You could call
entry.deleteCat(databaseId);

SQLite android column not found

my code is correct is assume but even though it gives error coloumn not found for _hour & _min:
package com.example.ifest;
public class ProfileView extends ListActivity{
int hour,min;
TimePicker tp ;
String e,e1;
static int p = 0;
Spinner spn ;
Button b1,b2,b3;
EditText et;
String str1;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list.add("Create");
openDB();
p++;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(position == 0){
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
tp = (TimePicker)build.findViewById(R.id.timePicker1_Dialog);
b3 = (Button)build.findViewById(R.id.button2_Dialog);
tp.setIs24HourView(true);
tp.setCurrentMinute(00);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
hour = tp.getCurrentHour();
min = tp.getCurrentMinute();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition(),hour,min);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
}
});
}
}
protected void addDB(String name,int id,int h,int m) {
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_name",name);
if(id == 0)
cv.put("_type","WIFI");
else if(id == 1)
cv.put("_type","BLUETOOTH");
else if(id == 2)
cv.put("_type","MEDIA");
cv.put("_hour", h);
cv.put("_min", m);
db.insert("_table", null , cv);
db.close();
}
private void openDB() {
if(p != 0){
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+ "_table",null);
c.moveToFirst();
while(c.moveToNext()){
list.add(c.getString(1));
Log.d("cursor", c.getString(1));
}
c.close();
db.close();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflate = getMenuInflater();
inflate.inflate(R.menu.string_main,menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
tp = (TimePicker)build.findViewById(R.id.timePicker1_Dialog);
b3 = (Button)build.findViewById(R.id.button2_Dialog);
tp.setIs24HourView(true);
tp.setCurrentMinute(00);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
hour = tp.getCurrentHour();
min = tp.getCurrentMinute();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition(),hour,min);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
}
});
break;
case R.id.item2:
break;
case R.id.item3:
Intent i = new Intent("com.example.ifest.ABOUTUS");
startActivity(i);
break;
case R.id.item4:
finish();
break;
}
return true;
}
}
and the database class is:
public class DBHandler extends SQLiteOpenHelper{
private static final String DB_NAME = "event_db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "_table";
private static final String EVENT_NAME = "_name";
private static final String EVENT_ID = "_no";
private static final String EVENT_TYPE = "_type";
private static final String EVENT_HOUR = "_hour";
private static final String EVENT_MINUTE = "_min";
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ EVENT_NAME + " TEXT NOT NULL, " + EVENT_TYPE + " TEXT NOT NULL, " + EVENT_HOUR +" INTEGER, " + EVENT_MINUTE + " INTEGER " + ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
is there anything wrong with the SQL exec statement means any space or something?
It looks like you have changed the table schema inside DBHandler#onCreate() after running the app at least once. If so you need to increment DB_VERSION = 2.
The database won't check the code inside onCreate() for a new schema on it's own, you need to tell the database to look for changes after you have made them. The easiest way to do this is by increasing the DB_VERSION.

Categories

Resources