Can't save chosen item from spinner to database - android

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)");

Related

How do I check spinner is empty?

I need to check if mine spinner is empty. But when there's a data inside of spinner, it's still showing me toast it's empty, does not contain any data. The main problem is that the spinner is already containing data from database,but program keeps adding new data after again app open.
Main activity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
databaseHelper db = new databaseHelper(getApplicationContext());
if (spinner.getCount() == 0){
Toast.makeText(MainActivity.this,"Spinner will be populated now",Toast.LENGTH_LONG).show();
db.insertData();
}else {
Toast.makeText(MainActivity.this,"Spinners is already populated",Toast.LENGTH_LONG).show();
}
loadData();
}
public void loadData(){
databaseHelper db = new databaseHelper(getApplicationContext());
List<String> labels = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, labels);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String label = adapterView.getItemAtPosition(i).toString();
Toast.makeText(adapterView.getContext(),"Selected: "+label,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Database
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," + COLUMN_2 + " TEXT," + COLUMN_3 + " TEXT," + COLUMN_4 + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_2, "1");
contentValues.put(COLUMN_3, "2");
contentValues.put(COLUMN_4, "3");
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else
return true;
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
labels.add(cursor.getString(2));
labels.add(cursor.getString(3));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return labels;
}
}
You should not do time consuming works like calling db from main application thread. call db asynchronously for example use AsyncTask.
you can get spinner items count like this:
int count = spinner.getAdapter() != null ? spinner.getAdapter().getCount() : 0;
I've been checked your code and always is calling db.insertData() because the spinner getCount at beginning always is 0.
So I let you some changes that I made in your MainActivity and also I created a method in Database class to know when I need to populate the db or not.
MainActivity
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private Spinner spinner;
private Database db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
db = new Database(getApplicationContext());
if(db.shouldPopulate()){
db.insertData();
}
loadData();
}
public void loadData(){
List<String> labels = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, labels);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(this);
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String label = adapterView.getItemAtPosition(i).toString();
Toast.makeText(adapterView.getContext(),"Selected: "+label,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Database
Here I changed the condition of the result in the insertData method for the result of the insertion.
And I created a method to know when you should insert the data.
public boolean insertData() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_2, "1");
contentValues.put(COLUMN_3, "2");
contentValues.put(COLUMN_4, "3");
return db.insert(TABLE_NAME, null, contentValues) != -1;
}
public boolean shouldPopulate(){
return getAllLabels().isEmpty();
}
I hope this code helps you.
IMPORTANT
You should wrap your db calls in a background handler, this is very important in Android apps for performance and as good practices.
Where are you adding data to your spinner? You just declare it:
spinner = (Spinner) findViewById(R.id.spinner);
You should use Adapter to add data to your Spinner:
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
And what spinner.getCount() means? May be it must refers to the adapter?

Data not being inserted in Table on Button Press

When I tap the button for inserting the data it says it is successful, but when I check my listview there is no data. But If I add again, then only the data is inserted.
Why is the data only inserted on the second time?
Thanks in advance! :D
This is my Database Helper class:
public static final String DB_NAME = "CartDB";
public static final String TABLE_NAME = "Orders";
public static final String COLUMN_ID = "id";
public static final String NAME ="name";
public static final String SIZE ="size";
public static final String QUANTITY ="quantity";
private static final int DB_VERSION = 1;
public cartDatabaseHelper(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " VARCHAR, "
+ SIZE + " VARCHAR, "
+ QUANTITY + " VARCHAR);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXIST Orders";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String name, String size, String quantity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SIZE,size);
contentValues.put(QUANTITY,quantity);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
And this is my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alcohol_list);
db = new cartDatabaseHelper(this);
GridAlcoholAdapter adapter = new GridAlcoholAdapter(alcoholType.this, images, names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = names.get(position);
String size = textSize.getText().toString().trim();
String quantityNumber = textQuantityNumber.getText().toString().trim();
String bottleCase = textBottleCase.getText().toString().trim();
String bottleCaseQuantity = textQuantity.getText().toString().trim();
textQuantity.setText(quantityNumber + " " + bottleCase);
db.addPerson(name,size,bottleCaseQuantity);
dialog.dismiss();
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.cartdialog);
dialog.setTitle("YOUR CART");
listView = (ListView) dialog.findViewById(R.id.listView);
final ListCartAdapter adapter = new ListCartAdapter(alcoholType.this, orderName, orderSize, orderQuantity);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
data.close();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
orderName.clear();
orderSize.clear();
orderQuantity.clear();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is my Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
public ListCartAdapter(Context context, ArrayList<String> orderName, ArrayList<String> orderSize, ArrayList<String> orderQuantity){
// public ListCartAdapter(Context context, ArrayList<String> orderName){
this.context = context;
this.orderName = orderName;
this.orderSize = orderSize;
this.orderQuantity = orderQuantity;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView name = (TextView) listView.findViewById(R.id.textOrderName);
TextView size = (TextView) listView.findViewById(R.id.textOrderSize);
TextView quantity = (TextView) listView.findViewById(R.id.textOrderQuantity);
name.setText(orderName.get(position));
size.setText(orderSize.get(position));
quantity.setText(orderQuantity.get(position));
return listView;
}
Why is the data only inserted on the second time?
The problem is in your while loop. When there is only one order then your while loop body will not be executed because you have used data.moveToNext() as condition. If your order count more than one, only then it will enter into the while loop.
ERROR:
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
SOLUTION:
if(data.moveToFirst())
{
do
{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while(data.moveToNext());
}
Hope this will help~
this is happening because you are adding data to orderName,orderSize and orderQuantity after setting adapter to listView. and you are not even calling
adapter.notifyDataSetChanged();
to let the adapter know that dataSet has changed
The problem is that the adapter doesn't know that you have added an element to the database.
After:
db.addPerson(name,size,bottleCaseQuantity);
you should make
adapter.notifyDataSetChanged()
Well guys I fixed the problem
I made a do-while in retrieving the data and it works!
do{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while (data.moveToNext());
thanks again to anyone who wanted and helped :D

Trying to Toast a single item from Database with OnItemSelected in a Spinner

The spinner has items that are dynamically added with two editText's and a Button. When the user inputs text into the first EditText it displays that text in the spinner. I am trying to Toast KEY_CALORIES from the second EditText that is sent into the database with OnItemSelected. I am trying to learn as a hobby so, an explanation would be great.
MainActivity. At the bottom is the OnItemSelected.
public class MainActivity extends Activity implements OnItemSelectedListener {
Button AddBtn;
EditText et;
EditText cal;
Spinner spn;
SQLController SQLcon;
ProgressDialog PD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AddBtn = (Button) findViewById(R.id.addbtn_id);
et = (EditText) findViewById(R.id.et_id);
cal = (EditText) findViewById(R.id.et_cal);
spn = (Spinner) findViewById(R.id.spinner_id);
spn.setOnItemSelectedListener(this);
SQLcon = new SQLController(this);
// opening database
SQLcon.open();
loadtospinner();
AddBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new MyAsync().execute();
}
});
}
public void loadtospinner() {
Cursor c = SQLcon.readData();
ArrayList<String> al = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(DBhelper.MEMBER_NAME));
al.add(name);
c.moveToNext();
}
ArrayAdapter<String> aa1 = new ArrayAdapter<String>(
getApplicationContext(), R.layout.spinner_item, R.id.textView1,
al);
spn.setAdapter(aa1);
// closing database
SQLcon.close();
al.add("Shit");
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
String name = et.getText().toString();
String calories = cal.getText().toString();
// opening database
SQLcon.open();
// insert data into table
SQLcon.insertData(name, calories);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
loadtospinner();
PD.dismiss();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
/* I am trying to Toast KEY_CALORIES from the database
* Tried many solution that failed and can't seem to grasp retrieving a single item from the database.
* Appreciate your help
*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
DataBase
public class SQLController {
private DBhelper dbhelper;
private Context ourcontext;
private SQLiteDatabase database;
public SQLController(Context c) {
ourcontext = c;
}
public SQLController open() throws SQLException {
dbhelper = new DBhelper(ourcontext);
database = dbhelper.getWritableDatabase();
return this;
}
public void close() {
dbhelper.close();
}
public void insertData(String name, String calories) {
ContentValues cv = new ContentValues();
cv.put(DBhelper.MEMBER_NAME, name);
cv.put(DBhelper.KEY_CALORIES, calories);
database.insert(DBhelper.TABLE_MEMBER, null, cv);
}
public Cursor readData() {
String[] allColumns = new String[] { DBhelper.MEMBER_ID,
DBhelper.MEMBER_NAME, DBhelper.KEY_CALORIES };
Cursor c = database.query(DBhelper.TABLE_MEMBER, allColumns, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
Helper
public class DBhelper extends SQLiteOpenHelper {
// TABLE INFORMATTION
public static final String TABLE_MEMBER = "member";
public static final String MEMBER_ID = "_id";
public static final String MEMBER_NAME = "name";
public static final String KEY_CALORIES = "calories";
// DATABASE INFORMATION
static final String DB_NAME = "MEMBER.DB";
static final int DB_VERSION = 2;
// TABLE CREATION STATEMENT
private static final String CREATE_TABLE = "create table " + TABLE_MEMBER
+ "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MEMBER_NAME + " TEXT NOT NULL," + KEY_CALORIES
+ " INT NOT NULL);";
public DBhelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
onCreate(db);
}
}
Edit It is Toasting the cal but every single cal entered into the database any suggestion to just show the cal that is clicked?
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
/*
* I am trying to Toast KEY_CALORIES Tried many solution that failed and
* can't seem to grasp retrieving a single item from the database.
* Appreciate your help
*/
SQLcon.open();
Cursor c = SQLcon.readData();
c.moveToFirst();
while (!c.isAfterLast()) {
String cal= c.getString(c.getColumnIndex(DBhelper.KEY_CALORIES));
Toast.makeText(getBaseContext(), cal+ "", Toast.LENGTH_LONG)
.show();
c.moveToNext();
}
SQLcon.close();
// closing database
}
First you need access to your adapter in order to get the selected string, so I would declare the aa1 adapter as a class field.
When you do that, you can access your adapter from the onItemSelected method:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
String your_selected_item=(String)aa1.getItem(pos);
Toast.makeText(getApplicationContext(),
your_selected_item, Toast.LENGTH_SHORT).show();
}
But I think your approach is not right... If you are listing DB-stored data, you should take a look at the CursorAdapter ;)

SQL table not found exception

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)

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