SQLite android column not found - android

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.

Related

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

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.

Remove item from database in recyclerview

I would like to add a feature that would allow me to remove a row from my recyclerview/database.
This feature is integrate to each item of my recyclerview as show in the following picture :
MySQLite.java:
public class MySQLite extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "character";
private static final int DATABASE_VERSION = 1;
private static final String CHARACTER_TABLE = "Ichar";
private static final String CHAR_TABLE = "create table " + CHARACTER_TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT, nom TEXT, prenom TEXT , numero TEXT)";
Context context;
public MySQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CHAR_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void InsererBDD(String nom, String prenom, String numero) {
Log.d("insert", "before insert");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues entree = new ContentValues();
entree.put("nom", nom);
entree.put("prenom", prenom);
entree.put("numero", numero);
db.insert(CHARACTER_TABLE, null, entree);
db.close();
Toast.makeText(context, "insérer entrée", Toast.LENGTH_LONG);
Log.i("insert", "after insert");
db.close();
}
public List<Character> donneesBDD() {
List<Character> modelList = new ArrayList<Character>();
String query = "select * FROM " + CHARACTER_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Character model = new Character();
model.setCharacter_Id(cursor.getInt(0));
model.setNom(cursor.getString(1));
model.setPrenom(cursor.getString(2));
model.setNumero(cursor.getString(3));
modelList.add(model);
} while (cursor.moveToNext());
}
Log.d("donnee character", modelList.toString());
return modelList;
}
public void supprimerLigne(int character_Id){
SQLiteDatabase db = getWritableDatabase();
db.delete(CHARACTER_TABLE , "id" + " = ?", new String[] { String.valueOf(character_Id)});
db.close();
}
public Character getCharacterById(int Id) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT " +
"nom" + "," +
"prenom" + "," +
"numero" +
" FROM " + CHARACTER_TABLE
+ " WHERE " +
"id" + "=?";
Character character = new Character();
Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(Id)});
if (cursor.moveToFirst()) {
do {
character.character_Id = cursor.getInt(cursor.getColumnIndex("id"));
character.nom = cursor.getString(cursor.getColumnIndex("nom"));
character.prenom = cursor.getString(cursor.getColumnIndex("prenom"));
character.numero = cursor.getString(cursor.getColumnIndex("numero"));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return character;
}
}
MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
static List<Character> characters;
static Context context;
MyAdapter(Context context,List<Character> characters)
{
this.characters = new ArrayList<Character>();
this.context = context;
this.characters = characters;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int itemType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_cell, null);
MyViewHolder myViewHolder = new MyViewHolder(itemLayoutView);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
holder.nom.setText(characters.get(position).getNom());
holder.prenom.setText(characters.get(position).getPrenom());
}
#Override
public int getItemCount() {
return characters.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener,View.OnClickListener, MenuItem.OnMenuItemClickListener {
public TextView nom;
public TextView prenom;
public ImageButton delete;
public MyViewHolder(final View itemLayoutView) {
super(itemLayoutView);
nom = ((TextView) itemLayoutView.findViewById(R.id.nom));
prenom = ((TextView) itemLayoutView.findViewById(R.id.prenom));
delete = (ImageButton) itemView.findViewById(R.id.delete);
itemLayoutView.setOnClickListener(this);
itemLayoutView.setOnCreateContextMenuListener(this);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(getAdapterPosition());
}
});
}
#Override
public void onClick(View view) {
Intent intent = new Intent(context, personne.class);
Bundle extras = new Bundle();
extras.putInt("position", getAdapterPosition());
intent.putExtras(extras);
context.startActivity(intent);
Toast.makeText(MyAdapter.context, "Vous avez sélectionné un item" + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("");
menu.add(0, v.getId(), 0, "Modifier Contact");
menu.add(0, v.getId(), 0, "Supprimer Contact");
}
#Override
public boolean onMenuItemClick(MenuItem item)
{
return true;
}
}
}
can you guide me?
Thanks a lot.
You need to remove the item from your array and then notifyDataSetChanged()
fragmentOrActivity.yourArray.remove(holder.getAdapterPosition());
fragmentOrActivity.yourAdapter.notifyDataSetChanged();
Hope that helps :-)
You should write your code in onBindViewHolder method like below.
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(characters.get(position).getId());
}
});

How to update list-view data at run time in android

I have list-view with check-box which loads data from database. And i have a button too, when i press a button spinner is popping up with 2 messages "EDIT" and "DELETE". Delete is working perfectly fine. and if i select Edit option and press OK then Edit-Text is coming in alert window with two button Ok and Cancel.
Now i want that Whatever i enter in edit-text and press Ok button a list-view data which is selected (Checked) should update with new text whatever i have entered in edit-text. So how to achieve this. Please help me. Any help would be appreciated. Thanks in advance.
My code for creating Database:
public class DataManipulatorClass {
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "mydatabaseclass.db";
private static final int DATABASE_VERSION = 1;
static final String TABLE_NAME = "newtableclass";
private static Context context;
static SQLiteDatabase db;
OpenHelper openHelper = null;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME
+ "(classname) values (?)";
public DataManipulatorClass(Context context) {
DataManipulatorClass.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulatorClass.context);
DataManipulatorClass.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulatorClass.db.compileStatement(INSERT);
//this.db = openHelper.getWritableDatabase();
}
public long insert(String classname) {
this.insertStmt.bindString(1, classname);
return this.insertStmt.executeInsert();
}
public void close() {
if (openHelper != null) {
openHelper.close();
}
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME,
new String[] { "id", "classname" }, null, null, null, null,
"classname asc");
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long rowId) {
/** this method deletes by id, the first column in your database */
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY, classname TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
My Activity class:
public class Classes extends Activity implements OnClickListener {
ImageView imageViewNewClass, imageViewDelete;
ListView mListView;
String[] stg1;
List<String[]> names2 = null;
DataManipulatorClass dataManipulator;
ArrayAdapter<CharSequence> adapterSpinner;
ArrayAdapter<String> adapter;
/** Sliding Menu */
boolean alreadyShowing = false;
private int windowWidth;
private Animation animationClasses;
private RelativeLayout classesSlider;
LayoutInflater layoutInflaterClasses;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classes);
imageViewNewClass = (ImageView) findViewById(R.id.newclass);
imageViewDelete = (ImageView) findViewById(R.id.deletemenu);
mListView = (ListView) findViewById(R.id.displaydata);
Display display = getWindowManager().getDefaultDisplay();
windowWidth = display.getWidth();
display.getHeight();
layoutInflaterClasses = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageViewDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
deleteMenuSpinner();
}
private void deleteMenuSpinner() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Classes.this);
final Spinner spinnerDelete = new Spinner(Classes.this);
alertDialog.setView(spinnerDelete);
adapterSpinner = ArrayAdapter.createFromResource(Classes.this,
R.array.delete_menu,
android.R.layout.simple_spinner_item);
adapterSpinner
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDelete.setAdapter(adapterSpinner);
alertDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Delete operation code.....
}
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Classes.this);
final EditText updateClass = new EditText(
Classes.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
updateClass.setLayoutParams(lp);
alertDialogBuilder.setView(updateClass);
alertDialogBuilder
.setTitle("Edit Operation");
alertDialogBuilder
.setMessage("Enter New Class Name")
.setCancelable(false)
.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
}
})
.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder
.create();
alertDialog.show();
}
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
findViewById(R.id.skirrmenu).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!alreadyShowing) {
alreadyShowing = true;
openSlidingMenu();
}
}
});
imageViewNewClass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Classes.this, Class_Create.class);
startActivity(intent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
// Toast.makeText(getApplicationContext(),
// "Listview item clicked", Toast.LENGTH_LONG).show();
SparseBooleanArray sp = mListView.getCheckedItemPositions();
StringBuffer str = new StringBuffer();
for (int i = 0; i < sp.size(); i++) {
if (sp.valueAt(i) == true) {
String s = ((TextView) mListView.getChildAt(i))
.getText().toString();
str = str.append(" " + s);
}
}
Toast.makeText(Classes.this,
"Selected items are " + str.toString(),
Toast.LENGTH_LONG).show();
// Intent intent = new Intent(Classes.this, PlayAudio.class);
// startActivity(intent);
}
});
dataManipulator = new DataManipulatorClass(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Class Name : " + name[1];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this,
R.layout.custom_list_item_multiple_choice, stg1);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setBackgroundResource(R.drawable.assignmentheader);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (dataManipulator != null)
dataManipulator.close();
}
}
You can try to use adapter.notifyDataSetChanged() when OK button pressed. But it will update whole list. If this is what you need, then here is the solution.
To update one list item you can try this:
private void updateView(int index, String updateText){
View v = yourListView.getChildAt(index -
yourListView.getFirstVisiblePosition());
TextView someText = (TextView) v.findViewById(R.id.sometextview);
someText.setText(updateText);
}

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)

Categories

Resources