I designed an app and on click in image view and show image in new activity if back app force close.
I add list view code and database code if need new activity code say.
list view code:
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class sharedlist extends ListActivity{
private String[] items;
private database db;
private Typeface nazanin;
private Typeface homa;
private SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedlist);
db=new database(this);
db.open();
items=new String[db.count("content")];
nazanin=Typeface.createFromAsset(getAssets(), "Font/nazanin.ttf");
homa=Typeface.createFromAsset(getAssets(), "Font/homa.ttf");
sp=getApplicationContext().getSharedPreferences("setting", 0);
setListAdapter(new AAD());
}
class AAD extends ArrayAdapter{
public AAD() {
super(sharedlist.this,R.layout.row,items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater in=getLayoutInflater();
View row=in.inflate(R.layout.row,parent,false);
final String li=db.Display_shared(position,0);
TextView username=(TextView) row.findViewById(R.id.row_username);
TextView maintext=(TextView) row.findViewById(R.id.row_maintext);
username.setText(db.Display_shared(position, 1).toString());
maintext.setText(db.Display_shared(position, 2).toString());
ImageView image=(ImageView) row.findViewById(R.id.row_image);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//new imageview("link",li).execute();
Intent ed=new Intent(sharedlist.this,showImage.class);
//new imageview("link",li).execute();
ed.putExtra("postid",li);
startActivity(ed);
}
});
if(sp.getString("font", "homa").equals("nazanin")){
maintext.setTypeface(nazanin);
}else if(sp.getString("font", "homa").equals("homa")){
maintext.setTypeface(homa);
}
if(sp.getString("size", "k").equals("k")){
maintext.setTextSize(18);
}else if(sp.getString("size", "k").equals("b")){
maintext.setTextSize(25);
}
return (row);
}
}
#Override
protected void onPause() {
super.onPause();
db.close();
}
}
and database :
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.widget.Toast;
public class database extends SQLiteOpenHelper {
public final String path="data/data/packagename/databases/";
public final String Name="database";
public SQLiteDatabase mydb;
private final Context mycontext;
public database(Context context) {
super(context, "database", null, 1);
mycontext=context;
}
#Override
public void onCreate(SQLiteDatabase arg0) {
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
public void useable(){
boolean checkdb=checkdb();
if(checkdb){
}else{
this.getReadableDatabase();
try{
copydatabase();
}catch(IOException e){
}
}
}
public void open(){
mydb=SQLiteDatabase.openDatabase(path+Name, null, SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
mydb.close();
}
public boolean checkdb(){
SQLiteDatabase db=null;
try{
db=SQLiteDatabase.openDatabase(path+Name, null, SQLiteDatabase.OPEN_READONLY);
}
catch(SQLException e)
{
}
return db !=null ? true:false ;
}
public void copydatabase() throws IOException{
OutputStream myOutput = new FileOutputStream(path+Name);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = mycontext.getAssets().open(Name);
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
public String Display(int row,int fild){
Cursor cu= mydb.query("content", null, null, null, null, null, null);
cu.moveToPosition(row);
String name=cu.getString(fild);
return name;
}
public Integer count(String table){
Cursor cu= mydb.query(table, null, null, null, null, null, null);
int s=cu.getCount();
return s;
}
public void insert(String id,String user,String matn){
ContentValues cv=new ContentValues();
cv.put("ID", id);
cv.put("username", user);
cv.put("matn", matn);
mydb.insert("content", "ID", cv);
}
public String Display_shared(int row,int fild){
Cursor cu= mydb.rawQuery("select * from content order by ID DESC",null);
cu.moveToPosition(row);
String name=cu.getString(fild);
return name;
}
}
log chat :
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: data/data/package name/databases/database
http://i.stack.imgur.com/iQOUp.png
Here:
final String li=db.Display_shared(position,0);
line causing issue because database open method called in onCreate method before setting Adapter for ListView and open method called again in getView method without closing previous connection which is opened in onCreate method.
if you are getting data from database according to position then open/close connection in getView method instead of onCreate method
or you can also get all data from table using one query and store in any data-container like ArrayList, Map,... instead of querying database many times.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am trying to add data to the SQLite database but when I add the data it gives me null pointer exception.
This is the error in the logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
enter code here
package com.llmago.autism;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class StartFragment extends Fragment {
private EditText edtName, edtAge, edtScore;
private Button save, load;
Db db = new Db(getActivity());
public StartFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_start, container, false);
initUI(view);
// Inflate the layout for this fragment
return view;
}
public void initUI(View view) {
edtName = view.findViewById(R.id.name);
edtAge = view.findViewById(R.id.age);
edtScore = view.findViewById(R.id.result);
save = view.findViewById(R.id.save);
save.setOnClickListener(v -> btnSaveAction(view));
}
public void btnSaveAction(View view) {
String name = edtName.getText().toString();
String age = edtAge.getText().toString();
String score = edtScore.getText().toString();
boolean result = db.insertData(name, age, score);
if (result == true) {
Toast.makeText(getActivity(), "Done", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
}
package com.llmago.autism;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class Db extends SQLiteOpenHelper {
public static final String databaseName = "autism.db";
public Db(#Nullable Context context) {
super(context, databaseName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table autism(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age TEXT, score TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS autiusm");
onCreate(db);
}
public boolean insertData(String name, String age, String score){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("age", age);
contentValues.put("score", score);
long result = sqLiteDatabase.insert("autism", null, contentValues);
if (result == -1)
return false;
else
return true;
}
}
Declare the mContext inside FragmentClass
Context mContext;
Change constructor from
public StartFragment(Context context) {
mContext = context;
db = new Db(mContext);
}
Also replace the db() constructor
public Db(#Nullable Context context) {
super(context, databaseName, null, 1);
this.getWritableDatabase();
}
Note: When you creating fragment instance you have to pass Activity Reference
My Database program works so far with submit and show data function. But deletion and modify database function is not working. I have attached the code for EventsDB.java and EventDetail.java and their resource layout file. Basically there is no problem with submit and show data part. i haven done the modify part and deletion part just din work.Please help.
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText etEvent,etEventDetail,etDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
etEvent=(EditText)findViewById(R.id.etEvent);
etEventDetail= (EditText)findViewById(R.id.etEventDetail);
etDate=(EditText)findViewById(R.id.etDate);
}
public void btnSubmit (View view)
{
try{
String event = etEvent.getText().toString();
String eventDetail = etEventDetail.getText().toString();
String date= etDate.getText().toString();
EventsDB db = new EventsDB(this);
db.open();
db.createEntry(event,eventDetail,date);
db.close();
Toast.makeText(MainActivity.this,"Successfully saved!!",Toast.LENGTH_LONG).show();
etDate.setText("");
etEventDetail.setText("");
etEvent.setText("");
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
Toast.makeText(this,"Please fill up all field",Toast.LENGTH_LONG).show();
}
}
public void btnShowEvents (View view)
{
startActivity(new Intent(this,EventData.class));
}
}
package com.cinrafood.teopeishen.databasedemo;
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 java.util.ArrayList;
public class EventsDB
{
public static final String KEY_ROWID ="_id";
public static final String KEY_EVENT="event_name";
public static final String KEY_EVENT_DESCRIPTIOM="event_description";
public static final String KEY_DATE="event_date";
private final String DATABASE_NAME="EventsDB";
private final String DATABASE_TABLE="EventsTable";
private final int DATABASE_VERSION=1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private ArrayList<Event> events;
public EventsDB(Context context)
{
ourContext= context;
}
private class DBHelper extends SQLiteOpenHelper
{
public DBHelper (Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
/*
CREATE TABLE EventsTable (_id INTEGER PRIMARY KEY AUTOINCREMENT,
event_name TEXT NOT NULL,event_description TEXT NOT NULL,
event_date DATE NOT NULL);
*/
String sqlCode="CREATE TABLE "+DATABASE_TABLE+" ("+
KEY_ROWID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_EVENT+" TEXT NOT NULL, "+
KEY_EVENT_DESCRIPTIOM+" TEXT NOT NULL, "+
KEY_DATE+" TEXT NOT NULL);";
db.execSQL(sqlCode);
}
}
public EventsDB open() throws SQLException
{
ourHelper = new DBHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
events= new ArrayList<Event>();
return this;
}
public void close()
{
ourHelper.close();
}
public long createEntry(String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.insert(DATABASE_TABLE,null,cv);
}
public ArrayList<Event> getData()
{
String [] columns = new String[]{KEY_ROWID,KEY_EVENT,KEY_EVENT_DESCRIPTIOM,KEY_DATE};
Cursor c = ourDatabase.query(DATABASE_TABLE,columns,null,null,null,null,null);
int iRowID = c.getColumnIndex(KEY_ROWID);
int iEvent = c.getColumnIndex(KEY_EVENT);
int iEventDescription = c.getColumnIndex(KEY_EVENT_DESCRIPTIOM);
int iDate = c.getColumnIndex(KEY_DATE);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
Event event = new Event(c.getInt(iRowID),c.getString(iEvent),c.getString(iEventDescription),c.getString(iDate));
events.add(event);
}
return events;
}
public long deleteEntry (String rowID){
return ourDatabase.delete(DATABASE_TABLE,KEY_ROWID+"=?",new String[]{rowID});
}
public long updateEntry(String rowID, String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.update(DATABASE_TABLE,cv,KEY_ROWID+"=?",new String[]{rowID});
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class EventData extends AppCompatActivity {
ListView lvEvents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_data);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try{
EventsDB db = new EventsDB(this);
db.open();
lvEvents= (ListView)findViewById(R.id.lvEvents);
lvEvents.setAdapter(new CustomAdapter(db.getData(),getApplicationContext()));
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location",position);
startActivity(intent);
return true;
}
};
lvEvents.setOnItemLongClickListener(click);
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
public class EventDetail extends AppCompatActivity {
EditText etTitlePage,etEventDetailPage,etDatePage;
Button btnDeleteEvent;
int location;
ArrayList<Event> events;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etTitlePage=(EditText) findViewById(R.id.etTitlePage);
etEventDetailPage=(EditText) findViewById(R.id.etEventDetailPage);
etDatePage=(EditText) findViewById(R.id.etDatePage);
btnDeleteEvent=(Button)findViewById(R.id.btnDeleteEvent);
try{
EventsDB db = new EventsDB(this);
db.open();
events=db.getData();
location = getIntent().getIntExtra("Location",0);
etTitlePage.setText(events.get(location).getEvent_name());
etEventDetailPage.setText(events.get(location).getEvent_description());
etDatePage.setText(events.get(location).getEvent_date());
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
btnDeleteEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
EventsDB db = new EventsDB(getApplicationContext());
db.open();
db.deleteEntry((location+1)+"");
db.close();
Toast.makeText(getApplicationContext(),"Successfully deleted!!",Toast.LENGTH_LONG).show();
}catch (SQLException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public Integer deleteContacts (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
Actually you have passed position of the item in ListView to delete that item from database which is not correct. You have to pass the rowId of database primary key to complete the delete operation.
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Retrieve Event from adapter
Event event = lvEvents.getAdapter().getItem(position);
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location", event.getRowId()); // get rowId from event.
startActivity(intent);
return true;
}
};
And execute delete operation using that rowId
db.deleteEntry(location + "");
and my XML file is
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
in these database i am getting values from database and displaying them in a listview.
my main activity is
package com.example.kern;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Second extends ListActivity {
DatabaseAdapter helper;
SQLiteDatabase db;
private CursorAdapter dataSource;
private static final String fields[] = { "Name", "Numb"};
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
helper=new DatabaseAdapter(this);
helper.open();
lv=(ListView)findViewById(android.R.id.list);
Cursor data = db.query("Mycon", fields,null, null, null, null, null);
dataSource = new SimpleCursorAdapter(this,
R.layout.activity_second, data, fields,
new int[] { R.id.name, R.id.number });
lv.setAdapter(dataSource);
}
}
and mydatabase adapter class is
package com.example.kern;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.kern.DatabaseAdapter;
import com.example.kern.DatabaseAdapter.DatabaseHelper;
public class DatabaseAdapter {
DatabaseHelper helper;
SQLiteDatabase db;
static final int VERSION=2;
static final String DATA_NAME="Mycontsc";
private static final String query = "create table Mycon(id Integer primary
key,Name text,Numb text)"; //the query has been changed
private final Context mCtx;
public DatabaseAdapter(Context ctx) {
this.mCtx = ctx;
}
//DatabaseHelper has become a subclass
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATA_NAME, null, VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DatabaseAdapter open() throws SQLException {
helper = new DatabaseHelper(mCtx);
db=helper.getWritableDatabase();
db=helper.getReadableDatabase();
return this;
}
public void close() {
helper.close();
}
public long AddDetail(String name,String num)
{
ContentValues vals=new ContentValues();
vals.put("Name",name);
vals.put("Numb", num);
long a=db.insert("Mycon", null, vals);
return a;
}
}
it is showing null pointer exception in logcat
09-18 10:32:02.631: E/AndroidRuntime(2286): FATAL EXCEPTION: main
09-18 10:32:02.631: E/AndroidRuntime(2286): java.lang.RuntimeException: Unable to
start activity ComponentInfo{com.example.kern/com.example.kern.Second}:
java.lang.NullPointerException
09-18 10:32:02.631: E/AndroidRuntime(2286): Caused by: java.lang.NullPointerException
09-18 10:32:02.631: E/AndroidRuntime(2286): at
com.example.kern.Second.onCreate(Second.java:29)
please check the program and give me the solution,it is showing exception,alerady there is values in the database and i am retriving them..
Cursor data = db.query("Mycon", fields,null, null, null, null, null);
You haven't initialized your db object.
Looks like you already have the initialization code i.e. SQLiteOpenHelper subclass and so on in DatabaseAdapter. Call getReadableDatabase() on the helper to get an SQLiteDatabase object you can run query() on.
I am trying to write a Race database where you would enter a race name and a race date, then click on that race name, and edit/delete it or the date. I am having trouble input the date. below is my LogCat error.
What am I doing wrong ?
//LOGCAT
12-08 20:15:35.710: I/Database(1648): sqlite returned: error code = 1, msg = near "FROM": syntax error
12-08 20:15:35.710: E/ERROR(1648): ERROR IN CODE: android.database.sqlite.SQLiteException: near "FROM": syntax error: , while compiling: SELECT _id, note FROM Races, date FROM Races
12-08 20:15:35.721: W/System.err(1648): android.database.sqlite.SQLiteException: near "FROM": syntax error: , while compiling: SELECT _id, note FROM Races, date FROM Races
12-08 20:15:35.730: W/System.err(1648): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
//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;
EditText editNote3=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);
editNote3 = (EditText)findViewById(R.id.myEditText3);
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(),editNote3.getText().toString());
}
else{
helper2.update(noteId2, editNote2.getText().toString(),editNote3.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="Races.db";
private static final int SCHEMA_VERSION=2;
String TAG = "INFORMATION";
public RaceHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Races (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, date TEXT);");
Log.i(TAG, "You are in the creation of db");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String note, String date) {
ContentValues cv=new ContentValues();
cv.put("note", note);
getWritableDatabase().insert("Races", "note", cv);
Log.i(TAG, "You have succesfully inserted into the db");
}
public void update(String id, String note, String date) {
ContentValues cv=new ContentValues();
String[] args={id};
cv.put("note", note);
getWritableDatabase().update("Races", cv, "_id=?", args);
}
public void delete(String id) {
getWritableDatabase().delete("Races", "_id=?", new String[] {id});
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Races, date FROM Races",
null));
}
public String getNote(Cursor c) {
return(c.getString(1));
}
public Cursor getById(String id) {
String[] args={id};
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Races WHERE _id=?",
args));
}
Change below line
getReadableDatabase().rawQuery("SELECT _id, note FROM Races, date FROM Races",
null)
to
getReadableDatabase().rawQuery("SELECT _id, note, data FROM Races",
null)
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.