Why am I getting this context and database error? - android

I am trying to...
create a simple listview that can be populated with data from an sqldatabase. The database works, I've seen it work with other code. The XML is fine and I really don't need to share it. When it comes to the XML, there is two buttons in the main activity: new and show. New sends you to the next activity to add to the list. Show will add data to the listview. That's all for the main activity. The other activity called NewEntry has a cancel button and a save button. It also has three editviews to help you add data.
Problems:
Right now it doesn't even compile without errors. The two errors are listed below in the main activity. If I comment out those two errors, I can get the application to run. when I open a new activity and try to save it, it crashes. They have to do with Context. I only sort of understand what Context does besides the fact that it is in everything.
This error has been solved see the bottom
The two compiler errors are in this code here. This is the main activity.
There are no other compiler errors, just logical ones.
I have pointed them out in the comments
""DATA BASE MANAGER CANNOT BE APPLIED TO LISTENER""
"CANNOT RESOLVE CONSTRUCTOR"
Also any explanations of Context will be appreciated.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
public class Main extends Activity {
private DatabaseManager mydManager;
private ListView productRec;
ArrayList<String> tableContent;
private LinearLayout addLayout;
ArrayList<String> arrayAdpt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
productRec=(ListView)findViewById(R.id.list);
Button newButton = (Button) findViewById(R.id.new_button);
Button showButton = (Button) findViewById(R.id.show_button);
Button newButton = (Button) findViewById(R.id.new_button);
newButton.setOnClickListener(new OnClickListener() {
public void onClick(View n) {
Intent x = new Intent(Main.this.getApplicationContext(), NewEntry.class);
startActivity(x);
}
});
showButton.setOnClickListener(new OnClickListener() { //Want this to launch new intent
public void onClick(View s) {
mydManager = new DatabaseManager(this); // <ERROR:
mydManager.openReadable(); //"DATA BASE MANAGER CANNOT BE APPLIED TO LISTENER"
tableContent = mydManager.retrieveRows();
productRec = (ListView)findViewById(R.id.list);
mydManager.retrieveRows(); //ERROR:
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent); //ERROR:CANNOT RESOLVE CONSTRUCTOR
productRec.setAdapter(arrayAdpt);
productRec.setVisibility(View.VISIBLE);
mydManager.close();
}
});
}
}
This is the NewEntry java class:
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
public class NewEntry extends Activity {
// public static final int REQUEST_CODE = 1;
private EditText titleView;
private EditText authorView;
private EditText priceView;
private Button doneButton;
private Button cancelButton;
private DatabaseManager mydManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
titleView = (EditText) findViewById(R.id.title_input);
authorView = (EditText) findViewById(R.id.author_input);
priceView = (EditText) findViewById(R.id.price_input);
doneButton = (Button) findViewById(R.id.done_button);
cancelButton = (Button) findViewById(R.id.cancel_button);
Intent i = this.getIntent();
//rec inserted, its a boolean in the other one
doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
mydManager = new DatabaseManager(NewEntry.this);
mydManager.addRow(Integer.parseInt(titleView.getText().toString()), authorView.getText().toString(),
Float.parseFloat(priceView.getText().toString())); ///sending in back to database
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(priceView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
mydManager.close();
titleView.setText("");
authorView.setText(""); //SOMETHING TO DO WITH DATA? maybe its blanking it out
priceView.setText("");
finish();
}
});
cancelButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
This is the database:
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class DatabaseManager {
public static final String DB_NAME = "shopping";
public static final String DB_TABLE = "products";
public static final int DB_VERSION = 1;
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (code INTEGER PRIMARY KEY, product_name TEXT, date FLOAT);";
private SQLHelper helper;
private SQLiteDatabase db;
private Context context;
public DatabaseManager(Context c){
this.context = c;
helper=new SQLHelper(c);
this.db = helper.getWritableDatabase();
}
public DatabaseManager openReadable() throws android.database.SQLException {
helper=new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
}
public void close(){
helper.close();
}
public boolean addRow(int t, String a, float p){
ContentValues newProduct = new ContentValues();
newProduct.put("title", t);
newProduct.put("author", a);
newProduct.put("price", p);
try{db.insertOrThrow(DB_TABLE, null, newProduct);}
catch(Exception e) {
Log.e("Error in inserting rows ", e.toString());
e.printStackTrace();
return false;
}
db.close();
return true;
}
public ArrayList<String> retrieveRows(){ ///Retrieves edit
ArrayList<String> productRows=new ArrayList<String>();
String[] columns = new String[]{"title", "author", "price"};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
productRows.add(Integer.toString(cursor.getInt(0)) + ", "+cursor.getString(1)+", "+Float.toString(cursor.getFloat(2)));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return productRows;
}
public class SQLHelper extends SQLiteOpenHelper {
public SQLHelper(Context c){
super(c, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Products table","Upgrading database i.e. dropping table and recreating it");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
}
Error when trying to retrieve rows:
04-11 22:08:25.552 21767-21767/com.example.alex.checkbox W/dalvikvm? threadid=1: thread exiting with uncaught exception (group=0x41e7cda0)
04-11 22:08:25.572 21767-21767/com.example.alex.checkbox E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.example.alex.checkbox, PID: 21767
android.database.sqlite.SQLiteException: no such column: title (code 1): , while compiling: SELECT title, author, price FROM products
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1448)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1295)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1166)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1334)
at com.example.alex.favoritebooks.DatabaseManager.retrieveRows(DatabaseManager.java:56)
at com.example.alex.favoritebooks.Main$2.onClick(Main.java:45)
at android.view.View.performClick(View.java:4654)
at android.view.View$PerformClick.run(View.java:19438)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)

In your newButton.setOnClickListener(...) code you are using the application Context when creating your Intent. Don't do that - instead use the Activity Context...
newButton.setOnClickListener(new OnClickListener() {
public void onClick(View n) {
// Simply use Main.this on the next line...
Intent x = new Intent(Main.this, NewEntry.class);
startActivity(x);
}
});
In your showButton.setOnClickListener(...) code you are passing a reference to the OnClickListener object to the constructor of your DatabaseManager and also when creating your ArrayAdapter...
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View s) {
mydManager = new DatabaseManager(this); //Here is the error
...
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent);
...
}
});
The this keyword refers to the current instance of any object which uses it - in this case, this refers to the OnClickListener which is not a Context. Also, as an aside, you're declaring a new ArrayAdapter variable in your OnClickListener code instead of using the one declared in the Activity. Change the code as follows...
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View s) {
mydManager = new DatabaseManager(Main.this);
...
arrayAdpt = new ArrayAdapter<String>(Main.this, android.R.layout.simple_list_item_1, tableContent);
...
}
});

Related

Android NullPointerException when i scroll PagerView with Tabs

I use the same code in another App and it works fine, i don't understand why here i receive a NullPointerException.
It's my first time with Fragments and maybe i write something wrong!
Below the code.
This is my Thrd Fragment
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
public class ThreeFragment extends Fragment {
public MySQLiteHelper db = new MySQLiteHelper(getContext());
public List<VotiEsami> esami;
public VotiEsamiAdapter adapter; //Adapter per caricare la listview di voti
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_three, container, false);
//Find the listview
final ListView listView = (ListView)view.findViewById(R.id.voti_listView);
//Get all exams inside database
esami = db.getVotiEsami();
adapter = new VotiEsamiAdapter(getContext(), R.layout.listview_voti_line, null);
listView.setAdapter(adapter);
//TODO gestire cancellazione del voto dal DB e dalla listview
Button nuovo_voto = (Button) view.findViewById(R.id.button_add_new_voto);
nuovo_voto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start Dialog for input the new vote
Intent myIntent = new Intent(getActivity(), DialogAddVotoEsame.class);
ThreeFragment.this.startActivityForResult(myIntent, 1);
}
});
return view;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
String result_nome = data.getStringExtra("result_name_esame"); //Take the materia from Dialog
int result_cfu = data.getIntExtra("result_cfu_esame", 1); //Take the materia from Dialog
int result_voto = data.getIntExtra("result_voto_esame", 1); //Take the materia from Dialog
//Add exam with vote to DB
db.addEsameVoto(new VotiEsami(result_nome, result_cfu, result_voto));
//Refresh list
List<VotiEsami> newesame = db.getVotiEsami();
//Aggiorno la Listview dell'activity con il nuovo inserimento
esami.clear();
esami.addAll(newesame);
adapter.notifyDataSetChanged();
}
}
}//onActivityResult
}
And here i have how manage the DB
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
//Database version
private static final int DATABASE_VERSION = 1;
//Database name
private static final String DATABASE_NAME = "agendaDB";
//Materie table name
public static final String TABLE_VOTI_ESAMI = "esami";
//Table_voti_esami columns
public static final String COLUMN_NOME_ESAME = "nome_esame";
public static final String COLUMN_CFU_ESAME = "cfu_esame";
public static final String COLUMN_VOTO_ESAME = "voto_esame";
//Stringa di creazione tabelle per database
//Tabella voti esami
private static final String CREATE_VOTO_ESAME_TABLE = "CREATE TABLE "
+ TABLE_VOTI_ESAMI + "("
+ COLUMN_NOME_ESAME + " TEXT,"
+ COLUMN_CFU_ESAME + " INTEGER,"
+ COLUMN_VOTO_ESAME + " INTEGER" + ")";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_VOTO_ESAME_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VOTI_ESAMI);
// Create tables again
onCreate(db);
}
//Restituisco tutti gli esami dati
public List<VotiEsami> getVotiEsami(){
List<VotiEsami> esamiList = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_VOTI_ESAMI;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor != null) {
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
VotiEsami esami = new VotiEsami();
esami.set_nome_esame(cursor.getString(0));
esami.set_cfu(Integer.parseInt(cursor.getString(1)));
esami.set_voto(Integer.parseInt(cursor.getString(2)));
// Adding materia activity voti to list
esamiList.add(esami);
} while (cursor.moveToNext());
}
}else{
return null;
}
// return contact list
return esamiList;
}
// Aggiunta nuova materia sull activity voti
public void addEsameVoto(VotiEsami esam) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NOME_ESAME, esam.get_nome_esame());
values.put(COLUMN_CFU_ESAME, esam.get_cfu());
values.put(COLUMN_VOTO_ESAME, esam.get_voto());
// Inserting Row
db.insert(TABLE_VOTI_ESAMI, null, values);
db.close(); // Closing database connection
}
}//Chiudo classe
With the same DB, and same methods works withouth NullPointerException in another App (With simple Activitys)
And another mistery(for me):
I have 5 Fragments, for the First, no problem i can see it, but if i go to the others (2,3,4 or 5) i get always the same error, and as you can see in the Log it's always write:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.application.ddz.agendauniversitaria.MySQLiteHelper.getVotiEsami(MySQLiteHelper.java:70)
at com.application.ddz.agendauniversitaria.ThreeFragment.onCreateView(ThreeFragment.java:48)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Can someone tell me where is my epic fail?
Thanks.
I think you might need to initialise db object in your onCreate() method.
onCreate()
The system calls this when creating the fragment. Within
your implementation, you should initialize essential components of the
fragment that you want to retain when the fragment is paused or
stopped, then resumed.
So you can do it like this:
public class ThreeFragment extends Fragment {
public MySQLiteHelper db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new MySQLiteHelper(getContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Your code
esami = db.getVotiEsami();
}
}

Eclipse LogCat Error about "no such table" SQLite

I am trying to write a Race database where you would enter a race name, then click on that race name, and edit/delete it.
So I am getting an error in my logcat (error code=1). It tells me there is no table created so I think I am not calling my variables correctly.
//LogCat
12-08 12:46:21.019: I/INFORMATION(650): You entered the insert method
12-08 12:46:21.019: I/Database(650): sqlite returned: error code = 1, msg = no such table: Note
12-08 12:46:21.062: E/Database(650): Error inserting note=ft
12-08 12:46:21.062: E/Database(650): android.database.sqlite.SQLiteException: no such table: Note: , while compiling: INSERT INTO Note(note) VALUES(?);
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
//View races java code
package com.CIS2818.tritracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class View_races extends Activity {
NoteAdapter adapter=null;
RaceHelper helper2=null;
Cursor dataset_cursor=null;
EditText editNote2=null;
String noteId2=null;
String TAG = "INFORMATION";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_view_races);
ListView list2=(ListView)findViewById(R.id.list2);
editNote2 = (EditText)findViewById(R.id.myEditText2);
helper2=new RaceHelper(this);
dataset_cursor=helper2.getAll();
startManagingCursor(dataset_cursor);
adapter=new NoteAdapter(dataset_cursor);
list2.setAdapter(adapter);
Button btnSimple2 = (Button) findViewById(R.id.btnSimple2);
btnSimple2.setOnClickListener(onSave);
Button btnDelete2 = (Button) findViewById(R.id.btnDelete2);
btnDelete2.setOnClickListener(onDelete);
list2.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
helper2.close();
}
private View.OnClickListener onSave=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.i(TAG,"You passed through the save method");
if (noteId2==null) {
helper2.insert(editNote2.getText().toString());
}
else{
helper2.update(noteId2, editNote2.getText().toString());
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private View.OnClickListener onDelete=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
if (noteId2==null) {
return;
}
else{
helper2.delete(noteId2);
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id2)
{
noteId2 =String.valueOf(id2);
Cursor c=helper2.getById(noteId2);
c.moveToFirst();
editNote2.setText(helper2.getNote(c));
}
};
class NoteAdapter extends CursorAdapter {
#SuppressWarnings("deprecation")
NoteAdapter(Cursor c) {
super(View_races.this, c);
}
#Override
public void bindView(View row, Context ctxt,Cursor c) {
NoteHolder2 holder=(NoteHolder2)row.getTag();
holder.populateFrom(c, helper2);
}
#Override
public View newView(Context ctxt, Cursor c,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder=new NoteHolder2(row);
row.setTag(holder);
return(row);
}
}
static class NoteHolder2 {
private TextView noteText2=null;
NoteHolder2(View row) {
noteText2=(TextView)row.findViewById(R.id.note2);
}
void populateFrom(Cursor c, RaceHelper helper) {
noteText2.setText(helper.getNote(c));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_view_races, menu);
return true;
}
//Button Method to return to the main Menu
public void Menu(View v){
Intent intent = new Intent(this, MainMenuActivity.class);
startActivity(intent);
}
//Button Method to go to the Race Activity
public void Races(View v){
Intent intent = new Intent(this, UpComingRaceActivity.class);
startActivity(intent);
}}
//RaceHelper java code
package com.CIS2818.tritracker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class RaceHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="note2.db";
private static final int SCHEMA_VERSION=1;
String TAG ="INFORMATION";
public RaceHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Note (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String note2) {
Log.i(TAG,"You entered the insert method");
ContentValues cv2=new ContentValues();
cv2.put("note", note2);
getWritableDatabase().insert("Note", "note", cv2);
}
public void update(String id, String note2) {
ContentValues cv2=new ContentValues();
String[] args={id};
cv2.put("note", note2);
getWritableDatabase().update("Note", cv2, "_id=?", args);
}
public void delete(String id2) {
getWritableDatabase().delete("Note", "_id=?", new String[] {id2});
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Notes",
null));
}
public String getNote(Cursor c2) {
return(c2.getString(1));
}
public Cursor getById(String id2) {
String[] args={id2};
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Note WHERE _id=?",
args));
}
}
It appears you have changed your SQL schema in your Java code but haven't informed SQLite. In order for your SQLiteOpenHelper class to use the new schema you provided in onCreate(), you need to upgrade your database. This is the most basic approach.
First add some functionality to onUpgrade():
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Note");
onCreate(db);
}
Now increment SCHEMA_VERSION to trigger an upgrade:
private static final int SCHEMA_VERSION=2;
Understand that SQLiteOpenHelper does not check the code inside onCreate() for you, you must tell SQLite there is a change by incrementing SCHEMA_VERSION.
In your insert method make the second value null. For example getWritableDatabase().insert("Note",null,cv2);
I have the same question as yours.I solved it.At first I rename the table that I create but do nothing with the CREATE_DATABASE order.Then I notice it. Although I corrected the order it does not works.So I add the onUpgrade method, and increment DATABASE_VERSION to a higher number,it works!!!Hope it works also for you.

How to select an item from ListView and see its corresponding id from SQLite database

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

Getting Force close when I try to open my golf scoreboard application

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.

How to use edittext.getText().toString()

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

Categories

Resources