i have created a database and run a query which add some elements to results.
I want the button that i have, to respond on click and show the results to a new black activity. I will post my current classes.
Sorry for everything but im very new to android programming. :)
package com.example.pota;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
public class createDatabase extends ListActivity{
private final String DATABASE_NAME = "potaDB";
private final String DATABASE_TABLE = "olaPota";
private final String DATABASE_TABLE2 = "favorites";
private final int DATABASE_VERSION = 1;
private SQLiteDatabase potaDB=null;;
//Kaleitai otan dimiourgeitai to activiy
public void onCreate(Bundle icicle, Context ctx){
super.onCreate(icicle);
ArrayList <String> results = new ArrayList<String>();
try {
//Dhmiourgei ti vasi an den uparxei alliws tin anoigei
this.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
//Dhmiourgei ena table sti vasi me ta ekseis paidia
potaDB.execSQL("CREATE TABLE IF NOT EXISTS" + DATABASE_TABLE + "(id INT PRIMARY KEY AUTOINCREMENT, name VARCHAR, category VARCHAR, info TEXT, difficulty INT);", null);
//Vazei eggrafes ston pinaka
potaDB.execSQL("INSERT INTO" + DATABASE_TABLE + "(name, category, info, difficulty)" + "VALUES ('Screwdriver', 'Pota', 'i klassiki vodka lemoni', 5);");
//Ena query pou tha mas gurisei ta stoixeia tou pinaka
Cursor c = potaDB.rawQuery("SELECT *" + "FROM" + DATABASE_TABLE,null);
//Pernoume ta dedomena tou pinaka pou xreiazomaste
int name1=c.getColumnIndex("name");
int category1=c.getColumnIndex("category");
int info1=c.getColumnIndex("info");
int difficulty1=c.getColumnIndex("difficulty");
//Pernei ta dedomena ekei pou deixnei o Cursor
String name = c.getString(name1);
String category = c.getString(category1);
String info = c.getString(info1);
int difficulty = c.getInt(difficulty1);
//Prosthetei ta trexontai dedomena sto results
results.add("Onoma Potou: " + name + "Katigoria Potou: " + category + "Suntagi: "+ info + "Duskolia: " + difficulty);
} catch(Exception e) {
System.out.println(e);
}finally {
if (potaDB != null)
potaDB.close();
}
}
}
And the Main Activity:
package com.example.pota;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
}
Ok, I'm not sure which Activity you want to use the button in but do something like:
public class MainActivity extends Activity {
Button myBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBtn = (Button) findViewById(R.id.my_button);
mBtn.setOnclickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, ReceivingActivity.class);
intent.putExtra("key", value); //name key whatever you want then value is whatever you are sending
startActivity(intent); //this starts the next activity through an intent
}
}
There are different ways to use onClick() but this is probably the most popular but it just depends on what you need. Here is one of my answers that shows how to do it using xml
You also need to Read about Intents and understand how to use them and what they are capable of.
To get the data in your other Activity you will do something like
public void onCreate()
{
...
Intent recIntent = getIntent();
String variableName = recIntent.getStringExtra("key");
}
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
There goes the code . I just cant figure out what is the problem. I am just taking the email and password as input from user and trying to store into a table named stu. The application crashes on clicking the sign in button which redirects to a next page using "intent" and inserting values into a table.
It would be of great help if problem could be identified that cause app to crash .
Thanks
Database Helper.java
package com.example.zain.smd1;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "student.db";
public static final String Table_name = "stu";
public static final String COL1 = "Id";
public static final String COL2 = "EMAIL";
public static final String COL3 = "PASS";
private static final String PASS = "PASS";
private static final String EMAIL = "EMAIL";
public DatabaseHelper(Context context) {
super(context,DB_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_name + " (Id INTEGER PRIMARY KEY AUTOINCREMENT, EMAIL TEXT , PASS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+Table_name);
onCreate(db);
}
public boolean insertdata(String email , String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(EMAIL,email);
content.put(PASS,pass);
long result = db.insert(Table_name,null,content);
if (result==-1){
return false;
}
else
return true;
}
}
Main Activity.java
package com.example.zain.smd1;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText et1,et2;
String email,pass;
RelativeLayout r1;
SharedPreferences sp;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1= (EditText) findViewById(R.id.eTemail);
et2 = (EditText) findViewById(R.id.eTpassword);
r1 = (RelativeLayout) findViewById(R.id.colorChange);
}
public void login(View view){
email = et1.getText().toString();
pass = et2.getText().toString();
if(email.equals("admin")&& pass.equals("admin")){
Toast.makeText(getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();
r1.setBackgroundColor(Color.RED);
/*sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor e= sp.edit();
e.putString("name",email);
e.putString("password",pass);
e.apply();*/
boolean ischecked = db.insertdata(et1.getText().toString(),et2.getText().toString());
if(ischecked==true) {
Toast.makeText(getApplicationContext(),
"Added",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
else {
r1.setBackgroundColor(Color.GREEN);
Toast.makeText(getApplicationContext(),
"Invalid password or email",Toast.LENGTH_SHORT).show();
}
/*
String name=sp.getString("name","");
String pass= sp.getString("password","");
et1.setText(name);
et2.setText(pass);
*/
}
}
Application crashes on inserting into SQLite database . I just couldn't figure out whats wrong
Try to uninstall the existing application from your Debugging device and then install it again. Sometimes when you change the structure of your table after installing it and again you are installing then it doesn't create new table.
you should try this...
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//add this line in your code..
db = new DatabaseHelper(this);
et1= (EditText) findViewById(R.id.eTemail);
et2 = (EditText) findViewById(R.id.eTpassword);
r1 = (RelativeLayout) findViewById(R.id.colorChange);
}
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);
Working on developing a Class for my android app that will randomly generate NPCs and their stats. Since these methods will be called in different activities figured putting them in their own class would be best. Yet having some trouble getting the cursors they contain to work correctly.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
public class startscreen extends Activity {
private dbhelper mydbhelper;
Intent intent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startscreen);
mydbhelper = dbhelper.getInstance(startscreen.this);
}
public void onClickNew(View v){
intent = new Intent(getBaseContext(), newgame.class);
startActivity(intent);
}
public void onClickLoad(View v){
//intent = new Intent(getBaseContext(), mainmenu.class);
//startActivity(intent);
Generator obj = new Generator();
obj.randomName();
}
I am calling the method on this bottom button to my main menu for easy testing.
import java.util.Random;
import android.database.Cursor;
import android.util.Log;
public class Generator {
public dbhelper mydbhelper;
public String randomName(){
Cursor name;
Random nameRandom = new Random();
int first = nameRandom.nextInt(171)+1;
name = mydbhelper.getRandomName(first); //This is where I get the error. "NullPointerException"
String firstName = name.getString(name.getColumnIndex(dbhelper.KEY_FIRST));
int last = nameRandom.nextInt(245)+1;
name = mydbhelper.getRandomName(last);
String lastName = name.getString(name.getColumnIndex(dbhelper.KEY_LAST));
String fullName = firstName + " " + lastName;
Log.e(fullName, "was the generated name");
return fullName;
}
}
If I take out the cursors and put in a stat string to return it works fine. So I'm handling this cursors incorrectly. Sadly Singleton and using methods from other classes is on of my short comings so hoping someone here will be able to explain what I'm doing wrong.
public Cursor getRandomName(int number){
return myDataBase.query(NAME_TABLE, new String[]{KEY_ID, KEY_FIRST, KEY_LAST},
KEY_ID + " = " + number , null, null, null, KEY_ID);
}
This is the cursor I'm working with, located in my dbhelper class.
mydbhelper in your Activity class is a different reference than the mydbhelper in your Generator class. You need to call mydbhelper = dbhelper.getInstance() in your Generator class or pass in the reference before you use it.
A quick way to do it would be:
public String randomName(dbhelper mydbhelp) {
// code
name = mydbhelper.getRandomName(first);
// code
name.close
}
Remember to close both your cursor and your database when you're done with it. Close the Cursor first.
Hi I am working with my application project.. It just happen that after I click on the login button, an error message pops out saying that Sorry! The application has stopped unexpectedly. Please try again. What is the error of this? please help thanks
This was my code for the data base of the user..
package com.gomez.android;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbuser{
public static final String user_name = "username";
public static final String user_password = "password";
public static final String row_id = "_id";
private static final String TAG = "UdbAdapter";
private DatabaseHelper UdbHelper;
private SQLiteDatabase Udb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table pages (_id integer primary key autoincrement, "
+ "username text not null, password text not null);";
private static final String DATABASE_NAME = "UserAccount";
private static final String DATABASE_TABLE = "User";
private static final int DATABASE_VERSION = 1;
private Context context = null;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS pages");
onCreate(db);
}
}
public dbuser(Context cntxt) {
this.context = cntxt;
UdbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
Udb = UdbHelper.getWritableDatabase();
}
public void close() {
UdbHelper.close();
}
public long createaccount(String username, String password)
{
Udb = UdbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(user_name, username);
initialValues.put(user_password, password);
return Udb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean Login(String username, String password)throws SQLException
{
Cursor mCursor = Udb.rawQuery(DATABASE_TABLE, new String[]{username,password});
if (mCursor != null){
if(mCursor.getCount() > 0){
return true;
}
}
return false;
}
}
and this was my login page code.....
package com.gomez.android;
import com.gomez.android.dbuser;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends Activity{
//Declare views
private EditText uname;
private EditText pword;
private Button btnlogin;
private Button btncancel;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set Activity Layout
setContentView(R.layout.login);
//Get EditText and Button References
uname = (EditText)findViewById(R.id.username);
pword = (EditText)findViewById(R.id.password);
btnlogin = (Button)findViewById(R.id.login_enter);
btncancel = (Button)findViewById(R.id.cancel);
//set Click Listener
btnlogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check Login
final String username = uname.getText().toString();
final String password = pword.getText().toString();
dbuser users = new dbuser(login.this);
users.open();
if(users.Login(username, password)){
if(username.equalsIgnoreCase(username)&& password.equalsIgnoreCase(password))
{
Toast.makeText(login.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
Intent i = new Intent(login.this, firstpage.class);
startActivity(i);
}
else{
Toast.makeText(login.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
users.close();
}
}
});
btncancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//close application
finish();
}
});
}
}
I can't be sure what the problem is with your code since you didn't provide any information from the LogCat, but it is possible that getWriteableDatabase() is returning a cached database when running the application (I often ran into this problem when implementing and testing a database for the first time).
To ensure this is not the problem, go to Settings -> Applications -> Manage Applications -> [Your Application] -> Clear Data, before running the application from Eclipse. This is an easy way to ensure you are working with your most up-to-date implementation during the early stages of implementing/testing the database.
This very well might not be the problem, but it is one of those things that you wouldn't expect to be the issue (which often leads to hours of frustration), so I thought I'd bring it up :).
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.