This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I'm trying to create a basic database and insert three users, but it doesn't work.
This is a class that creates the database
package com.example.matadoor.db1;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by matadoor on 06/08/2016.
*/
public class dbcreat extends SQLiteOpenHelper {
public final String tbname="t1";
public final String cid="id";
public static String cid2="test";
public final String user="username";
public final String creat="CREATE TABLE "+cid2+"("+cid+"INTEGER primery key AUTO_INCREMENT , "+user+" TEXT); ";
public dbcreat(Context context) {
super(context,cid2,null, 1);
}
public dbcreat(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(creat);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
And it's the other class which handles the database - opens it, closes it, and inserts into it
package com.example.matadoor.db1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by matadoor on 08/08/2016.
*/
public class dbhandler {
private dbcreat dbc;
private SQLiteDatabase sdb;
public dbhandler(Context context)
{
dbc=new dbcreat(context);
}
public void open()
{
sdb=dbc.getWritableDatabase();
}
public void close(){
dbc.close();
}
public String display(int row)
{
Cursor cu=sdb.query(dbc.tbname,null,null,null,null,null,null);
cu.moveToPosition(row);
String user=cu.getString(1);
return user;
}
public void insert(String user)
{
ContentValues cn=new ContentValues();
cn.put(dbc.user,user);
}
}
And the main class which has one Button for inserting a user into the db
package com.example.matadoor.db1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends AppCompatActivity {
Button btn;
dbhandler db;
dbcreat dbc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button)findViewById(R.id.ins);
// dbc.getWritableDatabase();
db.open();
db=new dbhandler(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String [] user={"ali","reza","ahmed"};
for(int i=0;i<user.length;i++)
{
db.insert(user[i]);
}
}
});
}
}
So this seems to be a error. You need to switch those two lines.
db.open(); // NullPointer here
db=new dbhandler(this);
Assuming there are no other errors with the code, this method is doing nothing to the database.
public void insert(String user)
{
ContentValues cn=new ContentValues();
cn.put(dbc.user,user);
}
You have to call sdb.insert with that cn variable.
Related
I'm new at the android studio. I tried creating SQLite Database but when I try inserting data android studio cannot resolve it. i also tried MainActivity.this and getApplicationContext instead of db=new DatabaseHelper(this); on this line. and on device monitor, it isn't creating a database file
MainActivity.java
package com.example.lenovo.sqlite_2_deneme;
import android.content.Context;
import android.media.midi.MidiDevice;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=new DatabaseHelper(this);
EditText et_name,et_surname,et_number;
Button btn_data;
et_name= (EditText) findViewById(R.id.et_isim);
et_surname= (EditText) findViewById(R.id.et_soyisim);
et_number= (EditText) findViewById(R.id.et_numara);
btn_data= (Button) findViewById(R.id.btn_veri);
btn_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertData();
}
});
}
}
and my DatabaseHelper class
package com.example.lenovo.sqlite_2_deneme;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import android.widget.TableLayout;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME= "student_info.db";
public static final String TABLE_NAME="student_table";
public static final String COL_1="ID";
public static final String COL_2="NAME";
public static final String COL_3="SURNAME";
public static final String COL_4="NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+ TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+ TABLE_NAME);
this.onCreate(db);
}
public Boolean DataInsert(String name, String surname, String number)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,number);
long sonuc= db.insert(TABLE_NAME,null,contentValues);
if(sonuc==-1)
return false;
else
return true;
}
}
Your database will be created at the instance when you call
SQLiteDatabase db=this.getWritableDatabase();
At the moment I dont see you have called this anywhere in your code. You have written a DataInsert method but it is not getting called in the code you have shared so far.
your'e sql query is wrong give the space in table (insert data),and also in onupgrade and there is no method insertData()
db.execSQL("CREATE TABLE "+ TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, NUMBER INTEGER)");
There is no method insertData() . You should use
DataInsert() method .
db=new DatabaseHelper(MainActivity.this);
EditText et_name,et_surname,et_number;
Button btn_data;
et_name= (EditText) findViewById(R.id.et_isim);
et_surname= (EditText) findViewById(R.id.et_soyisim);
et_number= (EditText) findViewById(R.id.et_numara);
btn_data= (Button) findViewById(R.id.btn_veri);
btn_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.DataInsert(et_name.getText().toString(),et_surname.getText().toString(),et_number.getText().toString());
}
});
FYI
void onCreate (SQLiteDatabase db)
Called when the database is created for the first time.
I have written a piece of code, which populates a database. However, when i execute that code in my android device or emulator, it gives an error "sorry app1 has stopped working" Please help me out to find out what's wrong.
the MainActivity.java file
package cu_coders.app1;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
public final EditText e=(EditText)findViewById((R.id.text1));
public final file1 f=new file1();
TextView t=(TextView)findViewById(R.id.textView1);
final myDB x=new myDB(this, null, null, 1);
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
Button enter=(Button)findViewById(R.id.button1);
Button delete=(Button)findViewById(R.id.button2);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = e.getText().toString();
f.set_name(s);
x.addItem(f);
t.setText(x.printTable());
}
});
}
}
A CLASS NAMED FILE1.JAVA
package cu_coders.app1;
/**
* Created by user pc on 03-10-2016.
*/
public class file1 {
private int _roll;
private String _name;
public file1() {
}
public file1(String _name) {
this._name = _name;
}
public int get_roll() {
return _roll;
}
public String get_name() {
return _name;
}
public void set_roll(int _roll) {
this._roll = _roll;
}
public void set_name(String _name) {
this._name = _name;
}
}
THE CLASS FOR DATABASE MANAGEMENT-- myDB.java
package cu_coders.app1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by user pc on 03-10-2016.
*/
public class myDB extends SQLiteOpenHelper {
private static int DATABASE_VERSION=1;
private static String DATABASE_NAME="file.db";
private static String TABLE_FILE1="class_cse";
public static String COLUMN_KEY="_key";
public static String COLUMN_NAME="_name";
public myDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query="create table "+ TABLE_FILE1 + "(" +
COLUMN_KEY + " INTEGER PRIMARY KEY "+
COLUMN_NAME+" TEXT "+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FILE1+";");
onCreate(db);
}
public void addItem(file1 f){
ContentValues cv=new ContentValues();
cv.put(COLUMN_NAME,f.get_name());
SQLiteDatabase db=getWritableDatabase();
db.insert(TABLE_FILE1,null,cv);
db.close();
}
/*public void deletItem(String item){
SQLiteDatabase db=getWritableDatabase();
db.execSQL("DELETE FROM "+TABLE_FILE1+" WHERE "+COLUMN_NAME+" =\" "+ item +"\";");
db.close();
} */
public String printTable(){
String dbstring="";
SQLiteDatabase db=getWritableDatabase();
String query="SELECT * FROM "+TABLE_FILE1+" WHERE 1;";
Cursor c=db.rawQuery(query,null);
c.moveToFirst();
while(!c.moveToLast()){
if(c.getString(c.getColumnIndex(COLUMN_NAME))!=null) {
dbstring += c.getString(c.getColumnIndex(COLUMN_NAME));
dbstring += '\n';
}
}
db.close();
return dbstring;
}
}
please help me out to find out what is wrong. thank you in advance.
you should change several items i guess...
change myDB Constructor to this :
public myDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and in mainActivity class change all global variable like this :
private EditText e ;
private file1 f ;
private TextView t;
and in oncreate() initial them :
e=(EditText)findViewById((R.id.text1));
f=new file1();
t=(TextView)findViewById(R.id.textView1);
i am trying to implement an app in which text entered in edittext is saved to the DB and then is displayed in a text field. But the app is crashing when i try to do this and i get a null pointer exception. This is my code
package com.example.dbex;
import java.sql.SQLOutput;
import java.sql.SQLPermission;
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 DBHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME="contactsmanager";
public static final String TABLE_CONTACTS="contacts";
public static final String KEY_ID="id";
public static final String KEY_NAME="name";
public static final String KEY_NUMBER="number";
public DBHandler(Context context) {
super(context,DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE_CONTACTS="CREATE TABLE "+TABLE_CONTACTS+"("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_NAME+" TEXT,"+KEY_NUMBER+" TEXT"+")";
db.execSQL(CREATE_TABLE_CONTACTS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+TABLE_CONTACTS);
onCreate(db);
}
public void addContact(Contacts contacts)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME, contacts.getname());
values.put(KEY_NUMBER, contacts.getnumber());
db.insert(TABLE_CONTACTS,null,values);
db.close();
}
public Contacts getContact(int id)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(TABLE_CONTACTS, new String[]{KEY_ID,KEY_NAME,KEY_NUMBER},KEY_ID+" =?",new String[]{String.valueOf(id)}, null, null, null, null);
Contacts contacts=null;
if(c!=null&&c.moveToFirst())
{
contacts=new Contacts(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
}
return contacts;
}
public void deleteContact(Contacts contacts)
{
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID+" =?", new String[]{String.valueOf(contacts.getID())});
db.close();
}
}
and the main activity is
package com.example.dbex;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button)findViewById(R.id.button1);
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
final TextView tv1=(TextView)findViewById(R.id.textView1);
final String _name=et1.getText().toString();
final String _phone=et2.getText().toString();
final DBHandler dbh=new DBHandler(getBaseContext());
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dbh.addContact(new Contacts(_name, _phone));
String contact1=(dbh.getContact(0)).getname();
tv1.setText(contact1);
}
});
}
#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;
}
}
i am getting the null pointer exception in the line
String contact1=(dbh.getContact(0)).getname();
where is my mistake?
thanks
Since you are telling you are able to insert the value, I assume your DB creation is correct You have hardcoded the id being queried to 0. You may not be having any value here. See this post to understand that even when you delete existing rows the auto increment ID could be continuing from the last used value instead of 0. So you could be returning a null value in this part of your code:
Contacts contacts=null;
if(c!=null&&c.moveToFirst())
{
contacts=new Contacts(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
}
return contacts;
I had a sample app in android version 4.2. I had set Breakpoints for each and every line. At the time of debugging, suddenly the debugging stopped saying that "The source attachment does not contain the source for the file SQLiteOpenHelper.class".
I attached the jar file and still it reports the error. Installed everything currently. But dont know the cause for this error.
This is my MainActivity.java
package com.example.newwaterreadingapp;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final android.content.Context Context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.mainLayout);
mainLayout.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right));
final LinearLayout readingLayout=(LinearLayout)findViewById(R.id.waterReading);
readingLayout.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right));
final LinearLayout pastDatePickerLayout=(LinearLayout)findViewById(R.id.PastDatePickerLayout);
pastDatePickerLayout.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right));
readingLayout.setVisibility(View.GONE);
pastDatePickerLayout.setVisibility(View.GONE);
Button AddWaterReading=(Button)findViewById(R.id.AddWaterReading); //click on + button.
AddWaterReading.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readingLayout.setVisibility(View.VISIBLE);
mainLayout.setVisibility(View.GONE);
TextView txtgetCurrentDate=(TextView)findViewById(R.id.currentDate);
final Calendar c=Calendar.getInstance();
txtgetCurrentDate.setText((c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DATE)+"/"+c.get(Calendar.YEAR));
}
});
TextView getPastDate=(TextView)findViewById(R.id.getDate);
getPastDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
readingLayout.setVisibility(View.GONE);
pastDatePickerLayout.setVisibility(View.VISIBLE);
}
});
Button savePastDate=(Button)findViewById(R.id.savePastDate);
savePastDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pastDatePickerLayout.setVisibility(View.GONE);
readingLayout.setVisibility(View.VISIBLE);
DatePicker getPastDatepicker=(DatePicker)findViewById(R.id.getPastDate);
int YY=getPastDatepicker.getYear();
int MM=getPastDatepicker.getMonth();
int DD=getPastDatepicker.getDayOfMonth();
TextView getPastDate=(TextView)findViewById(R.id.getDate);
getPastDate.setText((MM+1)+"/"+DD+"/"+YY);
}
});
Button saveWaterReadingToDB=(Button)findViewById(R.id.saveWaterReading);
saveWaterReadingToDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readingLayout.setVisibility(View.GONE);
mainLayout.setVisibility(View.VISIBLE);
TextView getPastDate=(TextView)findViewById(R.id.getDate);
TextView txtgetCurrentDate=(TextView)findViewById(R.id.currentDate);
TextView txtgetWaterReading=(TextView)findViewById(R.id.water_Reading);
CreateDB helper =new CreateDB(Context, "WaterElectricityReading.db", null, 1);
SQLiteDatabase DB;
DB=helper.getWritableDatabase();
String pastDate=getPastDate.getText().toString().trim();
String currentDate=txtgetCurrentDate.getText().toString().trim();
String waterReading=txtgetWaterReading.getText().toString().trim();
ContentValues values=new ContentValues();
values.put(CreateDB.COLUMN_NAME_READING_MODE,"Water");
values.put(CreateDB.COLUMN_NAME_PASTDATETIME, pastDate);
values.put(CreateDB.COLUMN_NAME_CURRENTDATETIME, currentDate);
values.put(CreateDB.COLUMN_NAME_READINGVALUE, waterReading);
DB.insert(CreateDB.TABLE_NAME, null, values);
Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_LONG).show();
DB.close();
helper.close();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and CreateDB.java
package com.example.newwaterreadingapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class CreateDB extends SQLiteOpenHelper{
private static final String DATABASE_NAME="WaterElectricityReading.db";
public static final String TABLE_NAME="Reading";
public static final String COLUMN_NAME_READING_ID="_Id";
public static final String COLUMN_NAME_READING_MODE="ReadingMode";
public static final String COLUMN_NAME_PASTDATETIME="PastDateTime";
public static final String COLUMN_NAME_CURRENTDATETIME="CurrentDateTime";
public static final String COLUMN_NAME_READINGVALUE="ReadingValue";
public static final int DATABASE_VERSION = 1;
public static String DB_PATH = "";
public CreateDB(Context context,String name, CursorFactory factory,
int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase DB){
final String CREATE_TABLE="create table if not exists "+ TABLE_NAME + "("+ COLUMN_NAME_READING_ID +" integer primary key autoincrement,"
+COLUMN_NAME_READING_MODE+" text not null,"+COLUMN_NAME_PASTDATETIME+" date not null,"+COLUMN_NAME_CURRENTDATETIME
+" date not null,"+COLUMN_NAME_READINGVALUE+" integer not null"+");";
DB.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Could anyone please suggest where I went wrong.
Thanks.
A .jar does not expose its source code by itself. You'll have to add the source code by yourself to be able to browse it.
You can be pretty sure though that the mistake will be on your own side, so you could question the use of debugging Android code :)
You can add it manually (don't remember how, Google) or use an Eclipse plugin which did a good job for me in the past; https://code.google.com/p/adt-addons/
Might be a little out-dated though.
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.