I am making an app for cooking. I made three SQL databases and I populate a list with a tabview.
This is the database
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Cook_tab_mains_data extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mains";
public Cook_tab_mains_data(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS mains (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT, " +
"disc TEXT, " +
"photo TEXT, " +
"prep TEXT, " +
"thumb TEXT, " +
"ingre TEXT, " +
"howto TEXT, " +
"info TEXT, " +
"mainId INTEGER)";
db.execSQL(sql);
ContentValues values = new ContentValues();
values.put("name", "Name 3");
values.put("disc", "here is the description");
values.put("photo", "stub.png");
values.put("ingre", "the ingredients of the mains");
values.put("howto", "how to make this thing");
values.put("info", "basically its this much calorie and such and such");
db.insert("mains", "name", values);
values.put("name", "Name 4");
values.put("disc", "here is the description");
values.put("photo", "stub.png");
values.put("thumb", "ic_launcher.png");
values.put("ingre", "the ingredients of the mains");
values.put("howto", "how to make this thing");
values.put("info", "basically its this much calorie and such and such");
db.insert("mains", "name", values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mains");
onCreate(db);
}}
As you can see my database is static.
Now I have a list activity that lists the items and another that details them:
import java.io.IOException;
import java.io.InputStream;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Cook_tab_mains extends ListActivity {
protected EditText searchText;
protected SQLiteDatabase db;
protected Cursor cursor;
protected ListAdapter adapter;
class CustomSimpleCursor extends SimpleCursorAdapter {
public CustomSimpleCursor(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
ImageView thumb = (ImageView) view.findViewById(R.id.thumb);
try {
InputStream bitmap = getAssets()
.open(cursor.getString(cursor
.getColumnIndexOrThrow("thumb")));
Bitmap bit = BitmapFactory.decodeStream(bitmap);
thumb.setImageBitmap(bit);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cook_tab_general);
db = (new Cook_tab_mains_data(this)).getWritableDatabase();
searchText = (EditText) findViewById (R.id.searchText);
EditText searchTo = (EditText)findViewById(R.id.searchText);
searchTo.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// autoclick
}
});
// || Query SQLite
cursor = db.rawQuery("SELECT _id, name, disc, thumb, prep FROM mains WHERE name LIKE ?",
new String[]{"%" + searchText.getText().toString() + "%"});
adapter = new CustomSimpleCursor(
this,
R.layout.cook_tab_generalist,
cursor,
new String[] {"name", "disc", "prep"},
new int[] {R.id.name, R.id.disc, R.id.prep});
setListAdapter(adapter);}
public void search(View view) {
// ||Query SQLite
cursor = db.rawQuery("SELECT _id, name, disc, thumb, prep FROM mains WHERE name LIKE ?",
new String[]{"%" + searchText.getText().toString() + "%"});
adapter = new CustomSimpleCursor(
this,
R.layout.cook_tab_generalist,
cursor,
new String[] {"name", "disc", "prep"},
new int[] {R.id.name, R.id.disc, R.id.prep});
setListAdapter(adapter);}
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this, Cook_tab_mains_details.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("MAINS_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
}
and then when an item is selected it shows details in this activity:
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class Cook_tab_mains_details extends Activity {
protected TextView Name;
protected ImageView Photo;
protected TextView Ingredients;
protected TextView HowTo;
protected TextView Information;
protected int mainId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cook_tab_generaldetails);
mainId = getIntent().getIntExtra("MAINS_ID", 0);
SQLiteDatabase db = (new Cook_tab_mains_data(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT emp._id, emp.name, emp.photo, emp.ingre, emp.howto, emp.info, emp.mainId, mgr.name mainsname, mgr.disc mainsdiscname FROM mains emp LEFT OUTER JOIN mains mgr ON emp.mainId = mgr._id WHERE emp._id = ?",
new String[]{""+mainId});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
Name = (TextView) findViewById(R.id.FoodName);
Name.setText(cursor.getString(cursor.getColumnIndex("name")));
Photo = (ImageView) findViewById(R.id.Photo);
try {
InputStream bitmap=getAssets().open(cursor.getString(cursor.getColumnIndexOrThrow("photo")));
Bitmap bit=BitmapFactory.decodeStream(bitmap);
Photo.setImageBitmap(bit);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Ingredients = (TextView) findViewById(R.id.Ingre);
Ingredients.setText(cursor.getString(cursor.getColumnIndex("ingre")));
HowTo = (TextView) findViewById(R.id.HowtoDo);
HowTo.setText(cursor.getString(cursor.getColumnIndex("howto")));
Information = (TextView) findViewById(R.id.Information);
Information.setText(cursor.getString(cursor.getColumnIndex("info")));
} }}
The problem: I can't seem to close() the database. I searched everywhere. I can't find an answer.
Every time I try this command:
public void close()
{
Cook_tab_mains_data.close();
}
it gives me this error and won't compile: Cannot make a static reference to the non-static method close() from the type SQLiteOpenHelper
So now what?
How do I close my database?
At the very end of your onCreate method in activity Cook_tab_mains_details, add cursor.close(); and db.close() to close the cursor and database respectively.
More preferably, you should load the data in onStart method and close the cursor+database in onStop method of your activity. (but thats just a suggestion)
In Android you don't need to close the db explicitly.It is auto-magically closed by android. In short, don't worry about closing db.
the error is you are trying to close the object you created using ClassName.close() which isnt a static method. You can call db.close() where db is the object whenever you need to. Cursors should managed by you though.
You have to call
cursor.close();
when you dont need them anymore.
In Cook_tab_mains add:
#Override
public void onDestroy() {
db.close()
}
Related
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've been going round in circles with this for days and I can't get my head around what's wrong.
With the following code, when you press the "yes" button to delete the item you touched, it shows everything and appears to do everything but the item is not removed from the list.
Activity class:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class NoteActivity extends Activity {
private ListView list;
DatabaseHandler db;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
db = new DatabaseHandler(this);
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
list = (ListView)findViewById(R.id.listView1);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View arg1, final int position,
long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(NoteActivity.this);
adb.setTitle("Delete Note?");
adb.setMessage(R.string.deleteNote);
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position + 1);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
adb.show();
}
});
}
And the Database helper:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "NoteDatabase.db";
public static final String NOTES_TABLE_NAME = "notes";
public static final String NOTES_COLUMN_ID = "id";
public static final String NOTES_COLUMN_NOTE = "note";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table notes " +
"(id integer primary key, note text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
public boolean insertNote (String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.insert("notes", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, NOTES_TABLE_NAME);
return numRows;
}
public boolean updateNote (Integer id, String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.update("notes", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteNote (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("notes",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllNotes()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from notes", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(NOTES_COLUMN_NOTE)));
res.moveToNext();
}
return array_list;
}
}
Everything else, such as adding a new item, works as it should.
Edit - It now deletes the one that is selected, but it doesn't always actually delete and there seems to be no pattern - I've added some system.out.printlns to get a clearer picture but it says that it is deleting the right one when it isn't.
In some Projects I faced the same Problem. So there are two possible Solutions. First, after removing Your data from database, also remove item from listview/Adapter and call notifyDataSetChanged:
db.deleteNote(position);
arrayAdapter.remove(arrayAdapter.getItem(itemToRemove));
arrayAdapter.notifyDataSetChanged();
So, my Problem was, that this sometimes doesn´t work, until now, I don´t know what I was doing wrong. Anyway, if this doesn´t work, refresh the whole data after deleting:
private void refreshData(){
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
list.setAdapter(arrayAdapter);
list.invalidateViews();
}
So this should look somehting like this in Your onClick:
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position);
refreshData();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
This is just from scratch, I can´t test the code for now because I have no IDE here. So don´t forget to do some Workaround (like opening and closing database etc.).
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
I am quite new androids and seem to have came across a Force close on my app and have no idea how to solve it.
Basically a part of my golf app is a scoreboard that the hole the person is on and the amount of strokes taken.
My code works were you have 2 buttons, add and subtract and change the number that shows up in the EditText. A button is then clicked and submits the number into a listview.I'm now trying to get it so that there is 2 add, subtract buttons and edittext and when both numbers have been entered and button to submit is clicked, will show something like 'Your stroke was 2' 'On hole 1'
Here is the code for it
package com.uhi.myGolfApp;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class scoreboard extends Activity implements OnClickListener {
Button buttonPlus1;
Button buttonMinus1;
EditText editScore1;
Button buttonPlus;
Button buttonMinus;
Button buttonOk;
EditText editScore;
ListView scoreCard;
Cursor cursor;
SimpleCursorAdapter adapter;
Integer score=0;
Integer score1=0;
SharedPreferences prefs;
databaseHelper dbHelper;
SQLiteDatabase db;
Intent i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate UI from XML
setContentView(R.layout.scoreboard);
// Get a hang of UI components
buttonPlus1 = (Button)findViewById(R.id.buttonadd);
buttonMinus1 = (Button)findViewById(R.id.buttonsub);
editScore1 = (EditText)findViewById(R.id.score1);
buttonPlus = (Button)findViewById(R.id.add);
buttonMinus= (Button)findViewById(R.id.subtract);
buttonOk = (Button)findViewById(R.id.enter);
editScore = (EditText)findViewById(R.id.score);
scoreCard = (ListView)findViewById(R.id.scorePosted);
// Add onClick listeners
buttonPlus1.setOnClickListener(this);
buttonMinus1.setOnClickListener(this);
buttonPlus.setOnClickListener(this);
buttonMinus.setOnClickListener(this);
buttonOk.setOnClickListener(this);
// Get preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
// Initialize the database
dbHelper = new databaseHelper(this);
db = dbHelper.getWritableDatabase();
// Load the data (essentially executes a SELECT statement)
cursor = db.query(databaseHelper.tableName, null, null, null, null, null, null);
startManagingCursor(cursor);
// Set the list adapter
String[] from = {databaseHelper.colStrokes, databaseHelper.colHole};
int[] to = {R.id.textStroke, R.id.textHole};
adapter = new SimpleCursorAdapter(this, R.layout.golfscores, cursor, from, to);
scoreCard.setAdapter(adapter);
}
#Override
public void onRestoreInstanceState(Bundle inState) {
score = (inState!=null) ? inState.getInt("score",0) : 0;
score1 = (inState!=null) ? inState.getInt("score1",0) : 0;
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("score", score);
outState.putInt("score1", score1);
super.onSaveInstanceState(outState);
}
#Override
public void onClick(View src) {
switch(src.getId()) {
case R.id.buttonadd:
score1++;
break;
case R.id.buttonsub:
score1--;
break;
case R.id.add:
score++;
break;
case R.id.subtract:
score--;
break;
case R.id.enter:
// Save in DB
ContentValues values = new ContentValues();
values.put(databaseHelper.colHole, score1);
values.put(databaseHelper.colStrokes, score);
db.insert(databaseHelper.tableName, null, values);
cursor = db.query(databaseHelper.tableName, null, null, null, null, null, null);
startManagingCursor(cursor);
adapter.changeCursor(cursor);
score=0;
adapter.changeCursor(cursor);
score1=0;
break;
}
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
}
}
and the database
package com.uhi.myGolfApp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class databaseHelper extends SQLiteOpenHelper {
// DB constants
private static final String DB_NAME = "scoreboard.db";
private static final int DB_VERSION = 1; // Schema version
// Schema constants
public static final String tableName = "scoreboard";
public static final String colHole = "hole";
public static final String colStrokes = "strokes";
// Constructor
public databaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
//create the SQL table and the attributes it will hold
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table "+tableName +
" (_id integer not null primary key autoincrement, "+
colHole + " integer, "+ colStrokes+" integer)";
db.execSQL(sql);
}
// upgrade the database off the old version
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Also I dont know if this is any help but this appears in the LogCat = 'Caused by: java.lang.IllegalArgumentException: column 'hole' does not exist'
Appreciate any help =]
I would guess that you ran your code once, before you added the "hole" column, and that is the database that is being read. You need to delete your app's data (Settings -> Applications -> Your app) so that the newest version of the database is created. If you don't have the option to delete data then uninstall it.
I want to make it so that there is a ListView with a Button above it. The users clicks that button, and it opens a dialog with an EditText and an OK and Cancel button. When the user clicks OK, whatever text is entered into the EditText gets put into the SQLiteDatabase, which is reflected in the ListView.
I've already set up my SQLiteDatabase and have set an adapter for the List to show the SQLiteDatabase, but I need to figure out how to use the edittext.getText().toString() method to add to the SQLiteDatabase. I will need a code example.
If you need it, here's my main .java:
package com.gantt.shoppinglist;
import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ShoppingList extends ListActivity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DataHelper dataHelper = new DataHelper(this);
ListView lv = (ListView) findViewById(android.R.id.list);
SimpleCursorAdapter adapter = null;
final SQLiteDatabase db = dataHelper.selectAll();
Cursor c = db.rawQuery("SELECT DISTINCT oid as _id,name FROM table1 ORDER BY name", null);
if (c.moveToFirst()) {
String[] columnNames = new String[]{"name"};
int[] list = new int[]{android.R.id.list};
adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, c, columnNames, list);
}
lv.setAdapter(adapter);
Button button1main = (Button) findViewById(R.id.add);
button1main.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog additem = new Dialog(ShoppingList.this);
additem.setContentView(R.layout.maindialog);
final EditText et = (EditText)additem.findViewById(R.id.edittext);
additem.setTitle("Type your item");
additem.setCancelable(true);
et.setHint("Type the name of an item...");
Button button = (Button) additem.findViewById(R.id.cancel);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
additem.dismiss();
}
});
additem.show();
Button ok = (Button) additem.findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
et.getText().toString();
additem.dismiss();
et.setText("");
}
});
}
});
}
}
Here is my DataHelper class:
package com.gantt.shoppinglist;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DataHelper {
public static final String DATABASE_NAME = "items.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "table1";
public static final String KEY_ROWID = "_id";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public SQLiteDatabase selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return db;
}
public static String getDatabaseName() {
return DATABASE_NAME;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, getDatabaseName(), null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Using the current methods you have, and assuming that you understand the code that you used for the database adapter, just do this:
String item = et.getText().toString();// these two lines are the
dataHelper.insert(item); // only change you have to do
additem.dismiss();
et.setText("");
After doing this, you have to call the notifyDataSetChanged method of your SimpleCursorAdapter object.
A simple sample method for your DataHelper class:
public long createUser(String email, String password, String fullName) {
ContentValues initialValues = new ContentValues();
initialValues.put("email", email);
initialValues.put("password", password);
initialValues.put("fullName", fullName);
return mDb.insert(TABLE_NAME, null, initialValues);
}