Hey everyone,
I cannot jump from my launch-activity to my second activity and i don't know why. this is the error i get:
02-22 11:43:04.858: ERROR/AndroidRuntime(18335): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.Database/android.Database.projects}: android.database.sqlite.SQLiteException: no such column: _id: , while compiling: SELECT _id, Name, Comment, projects
this is my launch-activity:
package android.Database;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class projectsDatabase extends Activity {
/** Called when the activity is first created. */
SQLiteDatabase myDB = null;
final static String MY_DB_NAME ="projectsDatabase";
final static String MY_DB_TABLE = "projects";
static final int MENU_PROJECTS = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onCreateDBAndDBTabled();
setContentView(R.layout.main);
}
private void onCreateDBAndDBTabled(){
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE
+ " ( _id integer primary key autoincrement,"+
"Name varchar(100),"+
"Comment varchar(128),"+
"BookingDetails varchar(255),"+
"ProjectKind integer(3))"
+";");
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PROJECTS, 0, R.string.menuProjects)
.setShortcut('1', 'f')
.setIcon(R.drawable.icon);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_PROJECTS:
Intent iProjects= new Intent(this, projects.class);
startActivity(iProjects);
return true;
}
return false;
}
}
and this is the actiity i want to start when the menu-button is clicked:
package android.Database;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
public class projects extends ListActivity {
SQLiteDatabase myDB = null;
static final int MENU_NEW_PROJECT = 0;
public void onCreate(Bundle icicle){
super.onCreate(icicle);
myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);
Cursor c = myDB.rawQuery("SELECT _id, ColumnName, ColumnComment, " + projectsDatabase.MY_DB_TABLE + ";", null);
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter (this,
android.R.layout.simple_list_item_1,
c,
new String[] {"_id"},
new int []{android.R.id.text1});
adapter.setViewBinder (new ViewBinder (){
#Override
public boolean setViewValue(View view, Cursor theCursor, int column){
String ColumnName = theCursor.getString(1);//Name
String ColumnComment = theCursor.getString(2);//Comment
((TextView)view).setText(ColumnName + "," + ColumnComment);
return true;
}
});
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long _id){
super.onListItemClick(l, v, position, _id);
Intent i = new Intent(this, projects_New.class);
i.putExtra("_id", _id);
this.startActivity(i);
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_NEW_PROJECT, 0, R.string.menuNewProject)
.setShortcut('1', 'n')
.setIcon(android.R.drawable.ic_menu_add);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case MENU_NEW_PROJECT:
Intent iProjects_New = new Intent (this, projects_New.class);
startActivity (iProjects_New);
return true;
}
return false;
}
}
I really hope you can help me out again ;)
--------------------------------------------Edit-------------------------------------------
now i can save data but can't select anything from my listview... here is the code for my projects_new.class :
package android.Database;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class projects_New extends Activity{
SQLiteDatabase myDB = null;
static final int MENU_INSERT_PROJECT = 0;
static final int MENU_UPDATE_PROJECT = 0;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_new);
Spinner s1 = (Spinner) findViewById(R.id.cb_ProjectKind);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,
R.array.ProjectKind,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
if(getIntent().hasExtra("_id") == true){
long l = getIntent().getExtras().getLong("_id");
myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);
Cursor myCursor = myDB.rawQuery("SELECT _id, ColumnName, ColumnComment, ColumnBookingDetails, ColumnProjectKind FROM"
+ projectsDatabase.MY_DB_TABLE + "WHERE _id = " +l+ "", null);
startManagingCursor(myCursor);
int ColumnName = myCursor.getColumnIndex("ColumnName");
int ColumnComment = myCursor.getColumnIndex("ColumnComment");
int ColumnBookingDetails = myCursor.getColumnIndex("ColumnBookingDetails");
int ColumnProjectKind = myCursor.getColumnIndex("ColumnProjectKind");
myCursor.moveToFirst();
if (myCursor != null) {
if(myCursor.isFirst()){
EditText eName = (EditText)findViewById(R.id.ed_Name);
eName.setText(myCursor.getString(ColumnName));
EditText eComment = (EditText)findViewById(R.id.ed_Comment);
eComment.setText(myCursor.getString(ColumnComment));
EditText eBookingDetails = (EditText)findViewById(R.id.ed_BookingDetails);
eBookingDetails.setText (myCursor.getString(ColumnBookingDetails));
Spinner sProjectKind = (Spinner)findViewById(R.id.cb_ProjectKind);
sProjectKind.setSelection(myCursor.getInt(ColumnProjectKind), true);
}
}
}
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
if(getIntent().hasExtra("_id")== true)
{
menu.add(0,MENU_UPDATE_PROJECT, 0, R.string.menuUpdate)
.setShortcut('1', 's')
.setIcon(android.R.drawable.ic_menu_save);
}
else
{
menu.add(0, MENU_INSERT_PROJECT, 0, R.string.menuInsert)
.setShortcut('1', 's')
.setIcon(android.R.drawable.ic_menu_save);
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case MENU_INSERT_PROJECT:
EditText Name = (EditText)findViewById(R.id.ed_Name);
EditText Comment = (EditText)findViewById(R.id.ed_Comment);
EditText BookingDetails = (EditText)findViewById(R.id.ed_BookingDetails);
Spinner ProjectKind = (Spinner)findViewById(R.id.cb_ProjectKind);
int i = ProjectKind.getSelectedItemPosition();
if(Name.length()!= 0)
{
myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);
if(getIntent().hasExtra("id")== true)//update
{
long l = getIntent().getExtras().getLong("_id");
myDB.execSQL("UPDATE "+ projectsDatabase.MY_DB_TABLE+" SET "+
"name = '"+Name.getText().toString()+"', "+
"Comment = '"+Comment.getText().toString()+"', "+
"BookingDetails ='"+BookingDetails.getText().toString()+"', "+
"ProjectKind ='"+i+"', "+
"WHERE _id = "+l+";");
}
else //insert
{
myDB.execSQL("INSERT INTO "+ projectsDatabase.MY_DB_TABLE +"(Name, Comment, BookingDetails, ProjectKind)"
+"VALUES ('"+Name.getText().toString()+"', "+
"'"+Comment.getText().toString()+"', "+
"'"+BookingDetails.getText().toString()+"', "+
"'"+i+"')");
}
finish();
return true;
}
else
{
Toast toast = Toast.makeText(this, "Please enter a name for this Project!" , Toast.LENGTH_SHORT);
toast.show();
}
}
return false;
}
}
Thank you so much for all your effort and help :)
In your Projects class you defined the following line
Cursor c = myDB.rawQuery("SELECT _id, ColumnName,
ColumnComment, " + projectsDatabase.MY_DB_TABLE + ";", null);
because it' says, there's no colunm _id in your table, so pls check that _id is a column in your table.
Pls ensure a clolun _id exists or not
Related
I'm working on a app where saxophone players can choose a saxophone (soprano, alto, tenor or baritone). The database should output all the music pieces that are available for that specific saxophone, together with the composer and publisher.
I've used a prepopulated db (created with SQLite Manager) and used the SQLite Asset Helper.
The database (so far) has some 600 records.
Whenever I query the database (let's say on 'alto'), it takes some 10 seconds before the results are found.
I've tried many things: indexing (both in the db file as in the Java code), changed between sqlite-file and db-file, tried on a real device instead of emulator etc, etc.
Nothing seems to work... I hope someone out there can help me on this...
I use two java classes: MyDatabase and SQLiteOpenHelper. If you need more info, please let me know.
MyDatabase class:
package com.example.musicrepertoiredatabase2;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
SqliteAssetHelper helper = new SqliteAssetHelper();
private static final String DATABASE_NAME = "saxophone_repertoire.sqlite";
private static final String TABLE_NAME = "repertoire";
private static final int DATABASE_VERSION = 1;
private static final String ID = "id";
private static final String COMPOSER = "composer";
private static final String TITLE = "title";
private static final String PUBLISHER = "publisher";
private static final String SAXOPHONE = "saxophone";
private static final String ACCOMPANIMENT = "form";
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String saxSort = SqliteAssetHelper.chooseSax;
String composer = SqliteAssetHelper.chooseComposer;
Cursor result = db.rawQuery("SELECT Composer, id FROM " + TABLE_NAME
+ " WHERE " + SAXOPHONE + "='" + saxSort + "'", null);
return result;
}
}
My SQLiteAssetHelper class:
package com.example.musicrepertoiredatabase2;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SqliteAssetHelper extends ActionBarActivity implements
OnItemSelectedListener, OnClickListener {
TextView composer, title, saxophone, accompaniment, showInfo, count;
EditText etComposer, etTitle;
Spinner spinnerSaxophone, spinnerAccompaniment;
Button search, clear;
String[] arraySaxophone = { "Soprano", "Alto", "Tenor", "Baritone" };
String[] arrayAccompaniment = { "Solo", "Piano" };
public static String chooseSax = null;
public static String chooseComposer = null;
Handler updateBarHandler;
private MyDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateBarHandler = new Handler();
spinnerSaxophone = (Spinner) findViewById(R.id.spinner_saxophone);
spinnerSaxophone.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySaxophone);
spinnerSaxophone.setAdapter(adapter1);
spinnerAccompaniment = (Spinner) findViewById(R.id.spinner_accompaniment);
spinnerAccompaniment.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayAccompaniment);
spinnerAccompaniment.setAdapter(adapter2);
etComposer = (EditText) findViewById(R.id.et_composer);
etComposer.setHint(Html.fromHtml("<small>"
+ getString(R.string.hint_composer) + "<small>"));
etTitle = (EditText) findViewById(R.id.et_title);
etTitle.setHint(Html.fromHtml("<small>"
+ getString(R.string.hint_title) + "<small>"));
search = (Button) findViewById(R.id.btn_search);
clear = (Button) findViewById(R.id.btn_clear);
search.setOnClickListener(this);
clear.setOnClickListener(this);
showInfo = (TextView) findViewById(R.id.tv_showinfo);
count = (TextView) findViewById(R.id.tv_count);
db = new MyDatabase(this);
}
public void launchRingDialog() {
final ProgressDialog ringProgressDialog = ProgressDialog.show(this,
"Searching database...", "Please wait...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable(){
#Override
public void run(){
try{
Thread.sleep(5000);
}catch (Exception e){
}
ringProgressDialog.dismiss();
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
int choosePositionSax = spinnerSaxophone.getSelectedItemPosition();
switch (choosePositionSax) {
case 0:
chooseSax = "Soprano";
break;
case 1:
chooseSax = "Alto";
break;
case 2:
chooseSax = "Tenor";
break;
case 3:
chooseSax = "Baritone";
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_search:
launchRingDialog();
chooseComposer = etComposer.getText().toString();
Cursor result = db.getData();
if (result.getCount() == 0) {
Toast.makeText(this, "Nothing found", Toast.LENGTH_SHORT)
.show();
}
launchRingDialog();
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()) {
//buffer.append("Title: " + result.getString(2) + "\n");
buffer.append("Composer: " + result.getString(1) + "\n\n");
showInfo.setText(buffer);
int countFiles = result.getCount();
count.setText(Integer.toString(countFiles));
}
break;
case R.id.btn_clear:
showInfo.setText("");
etComposer.setText("");
etComposer.requestFocus();
break;
default:
break;
}
}
}
Well you have to wait for 5 seconds, why =) ?
Thread.sleep(5000);
Delete this line and your query will be faster!
I have seen that you have launchRingDialog() declared two times in your code so you have to wait for 10 seconds. Your query should last no more than milliseconds so probably you donĀ“t need any ProgressDialog.
I'd suggest adding an index to your table:
Create Index IF NOT EXISTS _index_saxophone on T_ResultsSummary(saxophone);
Here is my Code
When I retrieved data from Cursor manually it was fine result,
but when I create SimpleCursorAdapter and put a cursor into it, I gives me FATAL EXCEPTION
MainActivity
package com.example.dummy;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class MainActivity extends Activity {
private static final String T = "Main";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Student s = new Student(this);
s.insert("Jeevan");
s.insert("Wahab");
s.insert("Majid");
Cursor c = s.getAllStudents();
ListView l = (ListView) findViewById(R.id.listView);
String[] from = {DbTable.NAME};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c, from, to, 0);
l.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Student Class
package com.example.dummy;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
public class Student {
private static final String T = "Student";
private DbTable dbHelper;
private SQLiteDatabase db;
public Student(Context context) {
dbHelper = new DbTable(context);
db = dbHelper.getWritableDatabase();
}
public long insert(String name) {
ContentValues cv = new ContentValues();
cv.put(DbTable.NAME, name);
long insert = 0;
try {
insert = db.insert(DbTable.TABLE, null, cv);
} catch (SQLiteException e) {
Log.d(T, "insert " + e.getLocalizedMessage());
}
return insert;
}
public Cursor getAllStudents(){
String[] columns = {DbTable.ID, DbTable.NAME};
Cursor c = db.query(DbTable.TABLE,
columns,
null, null, null, null, null);
if (c.moveToFirst() ) {
return c;
}
return c;
}
}
DbTable Class
where table is created
package com.example.dummy;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbTable extends SQLiteOpenHelper {
public static final String TABLE = "STUDENT";
public static final String ID = "ID";
public static final String NAME = "NAME";
private static final String T = "DATABASE TABLE";
private final String CREATE_TABLE = "CREATE TABLE "+TABLE
+ " ( '" + ID + "' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
+ "'"+NAME + "' VARCHAR NOT NULL );";
public DbTable(Context context) {
super(context, "MYDB", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
Log.i(T, "database created");
}catch(SQLiteException e){
Log.d(T, "error onCreate "+e.getLocalizedMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL("DROP TABLE IF NOT EXISTS "+TABLE);
onCreate(db);
Log.i(T, "onUpgrade ");
}catch(SQLiteException e){
Log.d(T, "onUpgrade "+e.getLocalizedMessage());
}
}
}
The apk is a memo pad or something like that. First you can put the title and then the note and if you press the button "Save" the note is saved and it saves in database. And if you press the button "Notes", you can view a list with all notes saved in database and you can select all notes and in the top of screen, you can read how many notes are selected. Ok, it's fine but I need remove notes when the are selected and I press the button with bin icon in the top menu.
The code:
package com.example.u2tarea3;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AnotacionesOpenHelperSingleton extends SQLiteOpenHelper {
private static AnotacionesOpenHelperSingleton instancia = null;
private Context mCtx;
public static AnotacionesOpenHelperSingleton getInstance(Context ctx){
if(instancia == null){
instancia = new AnotacionesOpenHelperSingleton(ctx);
}
return instancia;
}
private AnotacionesOpenHelperSingleton(Context ctx) {
super(ctx,"anotaciones",null,2);
}
#Override
public void onCreate(SQLiteDatabase bd) {
StringBuilder sql = new StringBuilder();
sql.append("create table IF NOT EXISTS anotaciones (");
sql.append("_id integer primary key autoincrement,");
sql.append("texto text not null,");
sql.append("fecha text not null)");
bd.execSQL(sql.toString());
}
#Override
public void onUpgrade(SQLiteDatabase bd, int oldVersion, int newVersion) {
//bd.execSQL("drop table anotaciones");
bd.execSQL("ALTER TABLE anotaciones ADD titulo text");
bd.execSQL("UPDATE anotaciones SET titulo = 'sin titulo' WHERE titulo is NULL");
onCreate(bd);
}
}
package com.example.u2tarea3;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText editText;
EditText editTitulo;
Button btnGuardar;
Button btnAnotaciones;
SQLiteDatabase bd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton.getInstance(this);
bd = openHelperSingleton.getWritableDatabase();
editText = (EditText)findViewById(R.id.editText);
editTitulo = (EditText) findViewById(R.id.editTitulo);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnGuardar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
ContentValues valores = new ContentValues();
valores.put("texto", editText.getText().toString());
valores.put("fecha", sdf.format(c.getTime()));
valores.put("titulo", editTitulo.getText().toString());
bd.insert("anotaciones", null, valores);
editText.setText("");
}
});
btnAnotaciones = (Button) findViewById(R.id.btnAnotaciones);
btnAnotaciones.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ListAnotaciones.class);
startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
}
package com.example.u2tarea3;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ListAnotaciones extends ListActivity {
SQLiteDatabase bd;
Cursor cursor;
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton
.getInstance(this);
int cont = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelperSingleton.getReadableDatabase();
cursor = bd.rawQuery("SELECT * FROM anotaciones", null);
try {
String[] from = { "fecha", "titulo" };
int[] to = { R.id.anotacionesFecha, R.id.anotacionesTitulo };
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.anotacion, cursor, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
MenuInflater inflater = arg0.getMenuInflater();
inflater.inflate(R.menu.anotaciones, arg1);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch(arg1.getItemId()){
case R.id.delete_id:
//arg0.finish();
default:
break;
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
int seleccionados = getListView()
.getCheckedItemCount();
switch (seleccionados) {
case 1:
mode.setTitle("1 nota seleccionada");
break;
default:
mode.setTitle("" + seleccionados
+ " notas seleccionadas");
break;
}
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}
}
You'll need to remove the note from the database and the ListView, and then call ListViewAdapter.notifyDataSetChanged()
To delete from the datasource have a method in the class that deals with the datasource:
/**
* Delete a note given an id.
* #param id Key used to identify a note to delete.
*/
public void deleteNote(long id) {
System.out.println("Note deleted with id: " + id);
database.delete(ListOpenHelper.TABLE_MEMOS,
ListOpenHelper.ID + " = " + id,
null);
}
To refresh the ListView you could simply clear and re-add all the Views via the ListViewAdapter:
// Refresh adapter view with new data
ListAdapter.clear();
ListAdapter.addAll(dataSource.getAllNotes());
ListAdapter.notifyDataSetChanged();
Alternatively remove only a single element from the ListViewAdapter and call notifyDataSetChanged();.
I have a table on my database.
one of the field from that table is displayed as a listview in the main activity.
i have implemented the setOnItemClickListener to open the new activity to display other field values of that selected list item.
new activiy is successfully opened.
but i have trouble in displaying field values....
i have browsed many sites....
but nothing helped.....
i have displayed department names in listview...
in the new activity i need get the value of DEPT_LIST_COLUMN_ID and DEPT_LIST_COLUMN_NAME
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
private MyDBHelper mydb;
private SimpleCursorAdapter adapter;
public static final String Row_ID = "row_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//********************************//
//Begin of Database-Table1_Dept_List
//********************************//
ListView dplist=(ListView)findViewById(R.id.list_view);
//Instantiate table1_dept_list
mydb =new MyDBHelper(this, null, null,4);
SQLiteDatabase db =mydb.getReadableDatabase();
//Removing duplicate values from table1_dept_list
mydb.delete_dep_list();
//Inserting into table1_dept_list
mydb.add_dept_list("DLBIOCHEM","BioChemistry");
mydb.add_dept_list("DLBIOTECH","BioTechnology");
mydb.add_dept_list("DLBOT", "Botany");
mydb.add_dept_list("DLCHEM","Chemistry");
mydb.add_dept_list("DLCOM","Commerce");
mydb.add_dept_list("DLCS","Computer Science");
mydb.add_dept_list("DLECO","Economics");
mydb.add_dept_list("DLEDU","Education");
mydb.add_dept_list("DLENG","English");
mydb.add_dept_list("DLEVS","Environmental Science");
mydb.add_dept_list("DLFSN","Food Science and Nutrition");
mydb.add_dept_list("DLGEO","Geology");
mydb.add_dept_list("DLJMC", "Journalism and Massmedia Communication");
mydb.add_dept_list("DLLIS","Library and Information Science");
mydb.add_dept_list("DLMATH","Mathematics");
mydb.add_dept_list("DLMICRO","Microbiology");
mydb.add_dept_list("DLPE","Physical Education");
mydb.add_dept_list("DLPHY","Physics");
mydb.add_dept_list("DLPRIMS","Periyar Institute of Management Studies");
mydb.add_dept_list("DLPSY","Psychology");
mydb.add_dept_list("DLSOC","Sociology");
mydb.add_dept_list("DLTAM", "Tamil");
mydb.add_dept_list("DLTAD","Textile and Apparel Design");
mydb.add_dept_list("DLZOO","Zoology");
//list view
Cursor AllDeptList = mydb.get_dept_list();
String[] from=new String[] {
MyDBHelper.DEPT_LIST_COLUMN_NAME
};
int[] to=new int[] {R.id.dis_text};
adapter = new SimpleCursorAdapter(this,R.layout.disp_text,AllDeptList,from,to,0 );
dplist.setAdapter(adapter);
//********************************//
//end of Database-Table1_Dept_List//
//********************************//
dplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor = mydb.get_dept_list();
cursor.moveToPosition(position);
Intent intent_dp_list = new Intent(MainActivity.this,DepartmentDesignation.class);
intent_dp_list.putExtra(Row_ID,arg3);
startActivity(intent_dp_list);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
DepartmentDesignation.java
package com.example.contact;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DepartmentDesignation extends Activity {
private SimpleCursorAdapter adapter;
public static String d_id;
public static String d_name;
private String Row_id;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.disp_dept_desig);
TextView tx_id = (TextView)findViewById(R.id.id);
Intent extras = getIntent();
tx_id.setText(extras.getStringExtra(Row_id));
TextView tx_name=(TextView)findViewById(R.id.name);
tx_name.setText(d_name);
}
}
MyDBHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHelper extends SQLiteOpenHelper{
public static final String DEPT_LIST_TABLE1_NAME="tbl_dep_list";
public static final String DEPT_LIST_ROW_ID = "_id";
public static final String DEPT_LIST_COLUMN_ID = "fld_tb1_id";
public static final String DEPT_LIST_COLUMN_NAME="fld_tb1_list";
public MyDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, "contact_book.db", factory, 11);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(" CREATE TABLE " + DEPT_LIST_TABLE1_NAME + "(" + DEPT_LIST_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + DEPT_LIST_COLUMN_ID + " TEXT, " + DEPT_LIST_COLUMN_NAME + " TEXT ) " );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DEPT_LIST_TABLE1_NAME);
onCreate(db);
}
public void add_dept_list(String dl_id, String dep_list) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues(2);
values.put(MyDBHelper.DEPT_LIST_COLUMN_ID , dl_id);
values.put(MyDBHelper.DEPT_LIST_COLUMN_NAME,dep_list);
getWritableDatabase().insert(MyDBHelper.DEPT_LIST_TABLE1_NAME,null,values);
}
public int delete_dep_list(){
try{
SQLiteDatabase db =this.getWritableDatabase();
return db.delete(DEPT_LIST_TABLE1_NAME, null, null);
}
catch(Exception e){
e.printStackTrace();
}
return 0;
}
public Cursor get_dept_list(){
String[] from = new String[] {MyDBHelper.DEPT_LIST_ROW_ID,MyDBHelper.DEPT_LIST_COLUMN_ID,MyDBHelper.DEPT_LIST_COLUMN_NAME};
Cursor cursor = getReadableDatabase().query(MyDBHelper.DEPT_LIST_TABLE1_NAME, from,null,null,null, null, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}
}
On your onItemClick method, pass the values you need in an intent to open the activity.
Intent intent = new Intent("blah blah");
intent.putExtra(DEPT_LIST_COLUMN_ID, "value");
intent.putExtra(DEPT_LIST_COLUMN_NAME, "value");
Then on the opened activity, do:
extras.getStringExtra(DEPT_LIST_COLUMN_ID)
I have the following two files:
podatkovna_baza.java
package com.example.ultimate.basketball.stats;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class podatkovna_baza extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "baza5";
public podatkovna_baza(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase baza5) {
/*
* Create the employee table and populate it with sample data.
* In step 6, we will move these hardcoded statements to an XML document.
*/
String sql = "CREATE TABLE IF NOT EXISTS ekipe4 (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ime_ekipe TEXT, " +
"kratko_ime TEXT, " +
"kraj TEXT, " +
"slika TEXT )";
baza5.execSQL(sql);
ContentValues values = new ContentValues();
values.put("ime_ekipe", "Drustvo partizan");
values.put("kratko_ime", "DRP");
values.put("kraj", "Mirna");
values.put("slika", "jajaja");
baza5.insert("ekipe4", null, values);
}
#Override
public void onUpgrade(SQLiteDatabase baza5, int oldVersion, int newVersion) {
baza5.execSQL("DROP TABLE IF EXISTS ekipe4");
onCreate(baza5);
}
}
osnovni_meni.java
package com.example.ultimate.basketball.stats;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class osnovni_meni extends Activity {
protected SQLiteDatabase baza5;
protected Cursor cursor;
protected ListAdapter adapter;
protected ListView ekipe_list;
protected EditText searchtext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_osnovni_meni);
baza5 = (new podatkovna_baza(this)).getWritableDatabase();
//searchtext = (EditText) findViewById (R.id.searchText);
//searchText = (EditText) findViewById (R.id.searchText);
//employeeList = (ListView) findViewById (R.id.list);
}
public void hello(View view) {
//cursor = baza2.rawQuery("SELECT ime_ekipe, kratko_ime, kraj FROM ekipe2" , null);
ekipe_list = (ListView) findViewById (R.id.lista);
cursor = baza5.query("ekipe4", null, null, null, null, null,
"_id" + " ASC");
adapter = new SimpleCursorAdapter(
this,
R.layout.ekipe_layout,
cursor,
new String[] {"_id","kratko_ime","kraj"},
new int[] {R.id.ime_ekipe,R.id.kratko_ime,R.id.kraj});
ekipe_list.setAdapter(adapter);
String sadas=adapter.toStr
}
public void delete_byID(int id) {
baza5.delete("ekipe4", "_id"+"="+id, null);
}
public void delete_by_ime_ekipe(String ime) {
baza5.delete("ekipe4", "kraj"+"="+ime, null);
}
public int deleteAll() {
return baza5.delete("ekipe4", null, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_osnovni_meni, menu);
return true;
}
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
finish();
}
public void vibriraj()
{
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(30);
}
public void vpisi(View view)
{
ContentValues values1 = new ContentValues();
//values1.put("_id", "1");
values1.put("ime_ekipe", "Chicago Bulls");
values1.put("kratko_ime", "CHI");
values1.put("kraj", "Chicago");
baza5.insert("ekipe4", "kratko_ime", values1);
vibriraj();
}
public void vpisi_ekipo(View view)
{
vibriraj();
EditText novo_ime_ekipe = (EditText) findViewById (R.id.novo_ime_ekipe);
EditText novo_kratko_ime_ekipe = (EditText) findViewById (R.id.novo_kratko_ime_ekipe);
EditText novo_kraj_ekipe = (EditText) findViewById (R.id.novo_kraj_ekipe);
EditText novo_slika_ekipe = (EditText) findViewById (R.id.novo_slika_ekipe);
ContentValues values1 = new ContentValues();
values1.put("ime_ekipe", (novo_ime_ekipe.getText()).toString());
values1.put("kratko_ime", (novo_kratko_ime_ekipe.getText()).toString());
values1.put("kraj", (novo_kraj_ekipe.getText()).toString());
values1.put("slika", (novo_slika_ekipe.getText()).toString());
baza5.insert("ekipe4", "kratko_ime", values1);
vibriraj();
setContentView(R.layout.edit_teams);
}
}
Now I want to for example delete a row I select (get ID from list and corresponding ID from database) or edit a row. How do I do this? It's pretty easy to delete or edit a SQLite entry if you know the id from a database, but I do not.
Sorry for my English, as you can see, it's not my first language.
ekipe_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// your code here
}
});
Here in "position" you get the id of the item you've clicked.
So you need only to convert the id in ListView to the id in database.
Otherwise you will need to create custom adapter instead of SimpleCursorAdapter, and override the getView() method.
in the select query you have mentioned "SELECT * FROM ANSWER WHERE ID="
But you have to mention as " "SELECT * FROM answer WHERE ID"
Because table name is answer not ANSWER