How to resolve index out of bounds error with SQLite? - java

I'm trying to get data from SQLite databse and when I'm trying, my app crashes and the error is: "android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1".
What am I doing wrong?
This is my activity:
public class EventInfo extends AppCompatActivity {
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_info);
myDb=new DatabaseHelper(this);
SharedPreferences sp = getSharedPreferences("key", 0);
final String event_title=sp.getString("event_title", "");
final String event_date=sp.getString("event_date", "");
String event_content=sp.getString("event_content","");
String age_limit=sp.getString("age_limit","");
String event_hour=sp.getString("event_hour","");
String location_left=sp.getString("location_left","");
String location_right=sp.getString("location_right","");
TextView txt5=(TextView)findViewById(R.id.textView5);
TextView txt6=(TextView)findViewById(R.id.textView6);
TextView txt7=(TextView)findViewById(R.id.textView7);
TextView txt8=(TextView)findViewById(R.id.textView8);
TextView txt9=(TextView)findViewById(R.id.textView9);
TextView txt10=(TextView)findViewById(R.id.textView10);
TextView txt14=(TextView)findViewById(R.id.textView14);
txt5.setText(event_title);
txt6.setText(event_date);
txt7.setText(age_limit);
txt8.setText(event_content);
txt9.setText(event_hour);
txt10.setText("Press here for event location");
String votes_count=myDb.getVotesCount(event_title);
if(votes_count.equals("1")) {
txt14.setText("Cancel Attending");
}
else {
if(votes_count.equals("0")||votes_count.isEmpty()) {
txt14.setText("Accept Attending");
}
else
{
txt14.setText("Error");
}
}
txt10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EventInfo.this, MapsActivity3.class);
startActivity(intent);
}
});
txt14.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String votes_count=myDb.getVotesCount(event_title);
if(votes_count.equals("0")||votes_count.isEmpty()) {
boolean insert = myDb.insertData("1", event_title, event_date);
if (insert == true)
Toast.makeText(EventInfo.this, "You have accepted the arrival", Toast.LENGTH_LONG).show();
else
Toast.makeText(EventInfo.this, "Error", Toast.LENGTH_LONG).show();
}
else
{
if(votes_count.equals("1"))
{
boolean insert = myDb.insertData("0", event_title, event_date);
if (insert == true)
Toast.makeText(EventInfo.this, "You have canceled the arrival", Toast.LENGTH_LONG).show();
else
Toast.makeText(EventInfo.this, "Error, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(EventInfo.this, votes_count.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
}
}
And this is my DatabaseHelper Class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="usersDB.db";
public static final String TABLE_NAME="votes_table";
public static final String COL2="VOTESCOUNT";
public static final String COL3="EVENTTITLE";
public static final String COL4="EVENTDATE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (VOTESCOUNT TEXT, EVENTTITLE TEXT, EVENTDATE TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String votes_count, String event_title, String event_date){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COL2,votes_count);
contentValues.put(COL3,event_title);
contentValues.put(COL4, event_date);
long result=db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
{
return false;
}
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getEventTitles()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select EVENTTITLE from "+TABLE_NAME,null);
return res;
}
public Cursor getEventDate(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select EVENTDATE from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
return res;
}
public String getVotesCount(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
String votes_count=res.getString(0);
return votes_count;
}
}

You have to move the Cursor to the first row before you access data from it, and it's a good idea to check the return value of moveToFirst() as well to make sure that the Cursor has data. Also, be sure to close any Cursor when you're done with it:
public String getVotesCount(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
String votes_count = null;
if (res.moveToFirst()) {
votes_count =res.getString(0);
}
res.close();
return votes_count;
}
And add a null check for the return value:
String votes_count = myDb.getVotesCount(event_title);
if(votes_count != null && (votes_count.equals("0")||votes_count.isEmpty())) {
//...............

Related

sqlLite in android didnt insert my data to table

I dont know why i have return result = -1 after execute insertGasData. In other similiar structure the result was != -1, but there is = -1.
There is DatabaseHelper class and main class
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "car.db";
public static final String TABLE_NAME2 = "car_gas_table";
public static final String COL_G_1 = "GAS_ID";
public static final String COL_G_2 = "GAS_DATE";
public static final String COL_G_3 = "GAS_MILEAGE";
public static final String COL_G_4 = "FUEL_TYPE";
public static final String COL_G_5 = "FUEL_COST";
public static final String COL_G_6 = "FUEL_VOLUME";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + TABLE_NAME2 + " (GAS_ID INTEGER PRIMARY KEY AUTOINCREMENT, GAS_DATE TEXT, GAS_MILEAGE TEXT, FUEL_TYPE TEXT, FUEL_COST TEXT, FUEL_VOLUME TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
}
public boolean insertGasData(String date, String mileage, String fuel_type, String fuel_price, String fuel_volume) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_G_2, date);
contentValues.put(COL_G_3, mileage);
contentValues.put(COL_G_4, fuel_type);
contentValues.put(COL_G_5, fuel_price);
contentValues.put(COL_G_6, fuel_volume);
long result = sqLiteDatabase.insert(TABLE_NAME2, null, contentValues);
if (result == -1)
return false;
else return true;
}
there is a call method
i use there Strings to eliminate other mistakes but it doesnt help
public void AddRefuelrData() {
bDodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// boolean isInsert = myDb.insertGasData(eRefDate.getText().toString(), eRefMileage.getText().toString(), eRefType.getText().toString(), eRefPrice.getText().toString(), eRefVolume.getText().toString());
boolean isInsert = myDb.insertGasData("dd","mm", "tt", "pr", "vo");
if (isInsert == true)
Toast.makeText(MainActivity.this, "Data inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
});
}
after call method insertGasData i have return false
enter image description here
Are you sure the table is actually created properly?
Use Device File Explorer to check if the database is created or not.
that should help with narrowing down the problem.

Retrieve Data As String From SQLite Database in Android Studio

I want to save name in the SQLite Database and later in another activity I want to retrieve that name as a String Value. But I am not being able to get data from the database. Help me please. My code is given below,
Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public void onCreate(SQLiteDatabase db) {String createTable =
"CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT, " + COL2 +" TEXT)";
db.execSQL(createTable);}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
MainActivity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
AddData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
}
}
HomeActivity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
}
}
Here, in this home activity i want to get the username as a string but I don't know how to do that. Help me please...
To retrieve data, you run a query that extracts the data into a Cursor. The Cursor will consist of 0-n rows and will have as many columns as defined in the query. You then move through the rows and use the appropriate Cursor get????? methods to get the actual data.
As an example you could add the following method to your DatabaseHelper :-
public String getName(long id) {
String rv = "not found";
SqliteDatabase db = this.getWritableDatabase();
String whereclause = "ID=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COL2));
}
return rv;
}
The above can then be used by String name = mDatabaseHelper.getName(1);.
Note that this assumes that a row with an ID of 1 exists.
Your Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 +" INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT)"; // You have written ID inplace of COL1
public DatabaseHelper(Context context)
{
super(context,DB_NAME,null,1);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(createTable);
}
public boolean insertData(String name) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL2,name);
long result1 = sqLiteDatabase.insert(TABLE_NAME,null,contentValues1);
return result1 != -1;
}
public Cursor viewData()
{
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor ;
String query = "Select * from " +TABLE_NAME;
cursor= sqLiteDatabase.rawQuery(query, null);
return cursor;
}
Your Main Activity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
mDatabaseHelper.insertData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
}
Your Home Activity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
ArrayList<String> listItem;
ArrayAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.listView);
listItem = new ArrayList<>();
viewData1();
}
private void viewData1() {
Cursor cursor = mDatabaseHelper.viewData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
Log.i("message","Data got");
listItem.add(cursor.getString(1)); // Adding data received to a Listview
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
listView.setAdapter(adapter);
}
}
}
check it out this library
it is very easy to implement
https://github.com/wisdomrider/SqliteClosedHelper

Android Studio, how to retrieve data from Sqlite database and display it into textview?

I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}

How to retrieve integer data from SQLite and show it in textview?

I'm new in SQLite and I have this code that shows the points in textview which retrieves the data from the database and if I click the button, it should retrieve the data, add some integers and append it to the database. However whenever I run the app, the app crashes.
Here's my mainActivity
import android.widget.TextView;
public class MainActivity extends Activity {
DatabaseHelper mydb;
private static TextView txt_stars;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DatabaseHelper(this);
onButtonClickListener();
txt_stars = (TextView) findViewById(R.id.txtStars);
//I already clean my code here
}
public void onButtonClickListener {
button_next = (Button) findViewById(R.id.btnNext);
button_next.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage("You have earned 50 stars");
alert.setCancelable(false);
alert.setPositiveButton("next", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//retrieve data, add 50, append data and return to main with a textview of 50 stars. How do I do this?
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
}
);
}
}
Here's my DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "star.db";
public static final String TABLE_NAME = "stars_table";
public static final String COL1 = "stars";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + TABLE_NAME + "(" + COL1 + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(Integer stars) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, stars);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select stars from" + TABLE_NAME, null);
return res;
}
}
Thanks a lot!
your code getAllData() is wrong ...change it following format
public ArrayList<Model> getAllData() {
cartList.clear();//your arraylist
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from stars_table", null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
Model item = new Model();//your object
item.status = cursor.getString(cursor.getColumnIndex("stars")); //your variable
cartList.add(item);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}

SQlite delete function is not deleting entries

Im having trouble getting individual items to delete in a database my application is using. I know the method gets called, but nothing in my list is ever removed. Im not getting any errors which is making it tough to track down. Assistance would be awesome.
public class MainActivity extends Activity{
//Global Variables
ListView lv;
Intent addM, viewM;
public DBAdapter movieDatabase;
String tempTitle, tempYear;
int request_Code = 1;
int request_code2 = 2;
SimpleCursorAdapter dataAdapter;
Cursor cursor;
Button addButton;
long testID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creates the database
movieDatabase = new DBAdapter(this);
movieDatabase.open();
//movieDatabase.deleteAllMovies();
//creates the intents to start the sub activities
addM = new Intent(this, AddMovie.class);
viewM = new Intent(this, MovieView.class);
}
//handles the return of the activity addMovie
public void onActivityResult(int requestCode, int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
switch(requestCode)
{
case 1:
dbAddMovie(data.getStringExtra("title"),
data.getStringExtra("year"));
break;
case 2:
testID = data.getLongExtra("rowid", -1);
dMovie(testID);
break;
}
}
}
//adds item to the movie list
public void dbAddMovie(String mT, String mY)
{
movieDatabase.open();
movieDatabase.insertMovie(mT, mY);
Toast.makeText(this, "Movie: " + mT + " added to database",
Toast.LENGTH_SHORT).show();
}
//deletes an entry into the database
public void dMovie(long rowid)
{
//Toast.makeText(this, "Deleting: " + rowid,
Toast.LENGTH_SHORT).show();
movieDatabase.deleteMovie(rowid);
movieDatabase.getAllMovies();
}
//displays the database as a list
public void displayListView()
{
addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
cursor = movieDatabase.getAllMovies();
//columns to use
String[] columns = new String[]
{
movieDatabase.KEY_TITLE,
};
//xml data to bind the data to
int[] to = new int[]
{
R.id.column2,
};
//adapter to display the database as a list
dataAdapter = new SimpleCursorAdapter(this,
R.layout.complexrow, cursor, columns, to, 0);
//gets the List view resource
lv = (ListView) findViewById(R.id.movielist);
//sets the list view to use the adapter
lv.setAdapter(dataAdapter);
//handles the list click events
lv.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View
v, int position,
long id) {
Cursor cursor = (Cursor)
parent.getItemAtPosition(position);
Bundle mDet = new Bundle();
mDet.putString("title",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_TITLE)));
mDet.putString("year",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_YEAR)));
mDet.putInt("rId", position);
viewM.putExtras(mDet);
startActivityForResult(viewM, 2);
}
});
//dataAdapter.notifyDataSetChanged();
}
public void onResume()
{
super.onResume();
displayListView();
}
}
and my coresponding dbadapter class
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_YEAR = "year";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MovieListDB";
private static final String DATABASE_TABLE = "MoviesTable";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table MoviesTable (_id
integer primary key autoincrement, " +
"title text not null, year not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_CREATE);
} catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion +
"which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS MoviesTable");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insertMovie(String title, String year)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_YEAR, year);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "='" + rowID+"'", null ) >-1;
}
public Cursor getAllMovies()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_YEAR}, null, null, null, null, null);
}
public Cursor getMovie(long rowID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_YEAR}, KEY_ROWID + "=" + rowID, null, null, null, null, null);
if(mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateContact(long rowID, String title, String year)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_YEAR, year);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowID, null) > 0;
}
public void deleteAllMovies() {
int doneDelete = 0;
doneDelete = db.delete(DATABASE_TABLE, null, null);
}
}
You're using the position returned from your listview as the row id in your database. This won't necessarily match up with your autoincremented "_id" in your database. position is just what position in the list it is.
You might want to think about using movieDatabase.KEY_ROWID as the key for your intents. Right now I see a mix of "rowid", "rId", "_id", and KEY_ROWID. It would simplify thing to just use the same key everywhere when referring to the same thing.
It looks like you continuously add bundles to the viewM intent. Is that true? If that's not your intent, you should either create a new intent for each click, or remove the previous bundles first.
I'm assuming KEY_ROWID is actually the name of the column? Try the following:
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[] { String.valueOf(rowID) }) >-1;
}

Categories