Retrieve a specific row data in database Android - java

I think I have read pretty much all the answers about this topic without getting the right answer for my case.
I have a list view in one activity called Library. When I click on an item, I would like to retrieve the informations about the clicked item in another activity. I would like these information to be in different field.
You will probably understand a bit better with my code.
This is the Library activity, on which I have my listview of what I call "tags":
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
DatabaseHelper.java :
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;
public class DatabaseHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
private static final String TAG_ID = "_id"; // a column named "_id" is required for cursor
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public DatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aTagName, String aTagId, String aTagData) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(TAG_NAME, aTagName);
contentValues.put(TAG_MID, aTagId);
contentValues.put(TAG_DATA, aTagData);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + TAG_ID + " INTEGER PRIMARY KEY, " +
TAG_NAME + " TEXT, " + TAG_MID + " TEXT, " + TAG_DATA + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
And InfoTagActivity.java , this is in this activity that I want to get the information about the clicked item :
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
With the associated activity_info_tag.xml :
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/relativeLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/relativeLayout2"
android:paddingTop="10dp">
<TextView
android:id="#+id/tagId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_above="#+id/tagDate"
android:layout_toRightOf="#+id/tagIdText"
android:layout_toEndOf="#+id/tagIdText" />
<TextView
android:id="#+id/tagDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_alignTop="#+id/tagDateText"
android:layout_toRightOf="#+id/tagDateText"
android:layout_toEndOf="#+id/tagDateText"
android:paddingLeft="5dp"
android:paddingRight="5dp"/>
<TextView
android:id="#+id/tagInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_below="#+id/tagDate"
android:layout_toRightOf="#+id/tagInfoText"
android:layout_toEndOf="#+id/tagInfoText"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
</RelativeLayout>
My problem is that by now, when I click on a tag of the list view, it always give me the information about the first tag only. I would like to get the information about the tag on which I clicked instead.
Could someone help me on that ?
Thank you a lot for your answers !

Related

"Attempt to invoke virtual method on a null object reference" while displaying data from the sqlite database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I want to retrieve the details from the database and print them in one of the tabbed activity fragment using a textview.
However, I am getting null object reference. Any clues on why am I getting this error and what I should have done to avoid this kind of error?
This is my fragment (fragment_home_left.class) where I have to display the records from the database
package com.rishabh.admin.bucomp;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
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;
public class fragment_home_left extends android.support.v4.app.Fragment implements View.OnClickListener {
Login_Signup_DB_adapter db_adapter;
String TAG = "FRAGMENT_HOME_LEFT";
//Button addGroup ,addMember;
//EditText new_group_edit_text;
Button display_users;
TextView display_box;
String details_recieved;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_activity_home_left, container, false);
//addGroup = (Button) view.findViewById(R.id.button_add_Group);
display_users = (Button)view.findViewById(R.id.button_display_users);
//addMember = (Button) view.findViewById(R.id.button_display_users);
//new_group_edit_text = (EditText) view.findViewById(R.id.editText_fragment_left);
display_box = (TextView) view.findViewById(R.id.editText_displayBox);
//addMember.setOnClickListener(this);
display_users.setOnClickListener(this);
//addGroup.setOnClickListener(this);
//To display the records of all the users registered within the database
//Display_user_data();
return view;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button_display_users)
{
//details_recieved = new_group_edit_text.getText().toString().trim();
//Toast.makeText(getActivity(),"Member added "+details_recieved,Toast.LENGTH_LONG).show();
Log.i(TAG, "onClick: Display users button clicked, calling display function");
Fetch_user_data();
}else{
Log.i(TAG, "onClick: NO ID BUTTON");
}
}
private void Fetch_user_data() {
Log.i(TAG, "Fetch_user_data: CALLING FETCH USER DATA METHOD");
Cursor cursor = db_adapter.getAll_users();
Log.i(TAG, "Fetch_user_data: CURSOR RECIEVED SOMETHING");
Display_user_data(cursor);
}
private void Display_user_data(Cursor cursor) {
Log.i(TAG, "Display_user_data: CALLED DISPLAY_USER_DATA");
String message = "";
if(cursor!= null && cursor.getCount() > 0){
Log.i(TAG, "Display_user_data: DO WHILE LOOP WILL BE EXECUTED");
cursor.moveToFirst();
do{
int user_id;
String user_name,user_email,user_password;
user_id = cursor.getInt(db_adapter.USER_COL_ROW_ID);
user_name = cursor.getString(db_adapter.USER_COL_NAME);
user_email = cursor.getString(db_adapter.USER_COL_EMAIL);
user_password = cursor.getString(db_adapter.USER_COL_PASSWORD);
message = message+"id="+user_id+","+"name="+user_name+","+"email="+user_email
+","+"pass="+user_password+"\n";
Log.i(TAG, "Display_user_data: NEW MESSAGE STRING APPENDED");
}while(cursor.moveToNext());
cursor.close();
Log.i(TAG, "Display_user_data: CURSOR IS CLOSED");
}
Log.i(TAG, "Display_user_data: CALLING SET_DATA_EDIT_TEXT METHOD");
set_data_in_editText(message);
}
private void set_data_in_editText(String message) {
Log.i(TAG, "set_data_in_editText: NOW SETTING MESSAGE TO TEXT VIEW");
display_box.setText(message);
}
}
xml layout linked with the above fragment(fragment_main_activity_home_left.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/button_display_users"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="67dp"
android:layout_marginEnd="140dp"
android:background="#color/Material_red"
android:elegantTextHeight="true"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text="Display_users"
android:textColor="#android:color/background_light" />
<EditText
android:id="#+id/editText_displayBox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/button_display_users"
android:layout_alignParentStart="true"
android:layout_marginBottom="10dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
</RelativeLayout>
This is the database helper class that stores and interacts with the data in the sqlite database
package com.rishabh.admin.bucomp;
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;
public class Login_Signup_DB_adapter {
//Database constants area
private static final String TAG = "DATABASE ADAPTER";
public static final String DB_NAME = "bucomp_db";
public static final int DB_VERSION = 2;
//Current_active_user_id stores the id of the current user
public static long Current_active_user_id = -2;
//Current_active_group_id stores the group id of the current group
public static long Current_active_group_id = 0;
private final Context context;
private DBHelper MYDBHelper;
private SQLiteDatabase db_readable, db_writable;
//End of database constants area
//column names for USER
public static final String DB_TABLE_USER = "user_table";
public static final String USER_KEY_ROWID = "user_id";
public static final String USER_KEY_NAME = "user_name";
public static final String USER_KEY_EMAIL = "user_email";
public static final String USER_KEY_PASSWORD = "user_password";
//column number for all the columns created above
public static final int USER_COL_ROW_ID = 0;
public static final int USER_COL_NAME = 1;
public static final int USER_COL_EMAIL = 2;
public static final int USER_COL_PASSWORD = 3;
//USER_ALL_KEYS stores the list of all the columns created
public static final String[] USER_ALL_KEYS = {
USER_KEY_ROWID, USER_KEY_NAME, USER_KEY_EMAIL, USER_KEY_PASSWORD
};
//create table query to be used by the database helper
private static final String DB_CREATE_QUERY_USER =
"create table " + DB_TABLE_USER
+ " (" + USER_KEY_ROWID + " integer primary key autoincrement, "
+ USER_KEY_NAME + " text not null, "
+ USER_KEY_EMAIL + " text not null, "
+ USER_KEY_PASSWORD + " text not null"
+ ");";
//column names for GROUPS within USERS
public static final String DB_TABLE_GROUP = "group_table";
public static final String GROUP_KEY_ROWID = "group_id";
public static final String GROUP_KEY_NAME = "group_name";
public static final String GROUP_KEY_TOTAL_BUDGET = "group_budget";
public static final String GROUP_KEY_TOTAL_MEMBERS = "group_total_members";
public static final String GROUP_KEY_LINKED_USER_ID = "group_linked_user_id";
//column number for all the columns created above
public static final int GROUP_COL_ROW_ID = 0;
public static final int GROUP_COL_NAME = 1;
public static final int GROUP_COL_TOTAL_BUDGET = 2;
public static final int GROUP_COL_TOTAL_MEMBERS = 3;
//GROUP_ALL_KEYS stores the list of all the columns created
public static final String[] GROUP_ALL_KEYS = {
GROUP_KEY_ROWID,
GROUP_KEY_NAME,
GROUP_KEY_TOTAL_BUDGET,
GROUP_KEY_TOTAL_MEMBERS,
GROUP_KEY_LINKED_USER_ID
};
//create table query to be used by the database helper
private static final String DB_CREATE_QUERY_GROUP =
"create table " + DB_TABLE_GROUP
+ " (" + GROUP_KEY_ROWID + " integer primary key autoincrement, "
+ GROUP_KEY_NAME + " text not null, "
+ GROUP_KEY_TOTAL_BUDGET + " integer, "
+ GROUP_KEY_TOTAL_MEMBERS + " integer, "
+ GROUP_KEY_LINKED_USER_ID + " integer not null"
+ ");";
//column names for MEMBERS within GROUPS
public static final String DB_TABLE_MEMBER = "member_table";
public static final String MEMBER_KEY_ROWID = "member_id";
public static final String MEMBER_KEY_NAME = "member_name";
public static final String MEMBER_KEY_LINKED_GROUP_ID = "member_linked_group_id";
public static final String MEMBER_KEY_LINKED_USER_ID = "member_linked_user_id";
//column number for all the columns created above
public static final int MEMBER_COL_ROW_ID = 0;
public static final int MEMBER_COL_NAME = 1;
public static final int MEMBER_COL_LINKED_GROUP_ID = 2;
public static final int MEMBER_COL_LINKED_USER_ID = 3;
//MEMBER_ALL_KEYS stores the list of all the columns created
public static final String[] MEMBER_ALL_KEYS = {
MEMBER_KEY_ROWID,
MEMBER_KEY_NAME,
MEMBER_KEY_LINKED_GROUP_ID,
MEMBER_KEY_LINKED_USER_ID
};
//create table query to be used by the database helper
private static final String DB_CREATE_QUERY_MEMBER =
"create table " + DB_TABLE_MEMBER
+ " ("
+ MEMBER_KEY_ROWID + " integer primary key autoincrement, "
+ MEMBER_KEY_NAME + " text not null, "
+ MEMBER_KEY_LINKED_GROUP_ID + " integer not null, "
+ MEMBER_KEY_LINKED_USER_ID + " integer not null"
+ ");";
public Login_Signup_DB_adapter(Context context) {
this.context = context;
MYDBHelper = new DBHelper(context);
}
public Login_Signup_DB_adapter open_database(){
db_writable = MYDBHelper.getWritableDatabase();
db_readable = MYDBHelper.getReadableDatabase();
return this;
}
public void close_database(){
MYDBHelper.close();
}
//insert new user in the user table
public long SignUp_new_user(String UserName, String UserEmail, String UserPassword){
//set up contentValues to insert the data into the required DB
ContentValues contentValues = new ContentValues();
//feed data into the contentValues
contentValues.put(USER_KEY_NAME, UserName);
contentValues.put(USER_KEY_EMAIL, UserEmail);
contentValues.put(USER_KEY_PASSWORD, UserPassword);
//insert the data stored in the contentValues into the DB_USER
//The return statement will return the id of the newly entered user in the user table
//this is the reason why the return type is long
Log.i(TAG, "SignUp_new_user: WRITING NEW USER IN THE DATABSE");
return db_writable.insert(DB_TABLE_USER, null, contentValues);
}
public long Check_Login_user(String UserName, String UserPassword)
{
Log.i(TAG, "Check_Login_user: ENTERED Check_Login_user");
//db_readable = MYDBHelper.getReadableDatabase();
Log.i(TAG, "Check_Login_user: READABLE DB SET");
/* To verify if the user if already registered and take appropriate actions as below:
1. If the user is already registered and enters correct details, grant login access.
2. If the user is already registered but enters incorrect details, revoke access.
3. If the user is not registered, simply revoke the access.
NOTE: If possible, try to redirect the user to the signUp page if CASE 3 occurs.
*/
String where = USER_KEY_NAME+"=?";
String[] args = {UserName};
Log.i(TAG, "Check_Login_user: QUERYING DB FOR LOGIN");
Cursor cursor = db_readable.query(
DB_TABLE_USER,
USER_ALL_KEYS,
where,
args,
null,
null,
null
);
Log.i(TAG, "Check_Login_user: CURSOR POPULATED");
if (cursor.getCount() > 0)
{
Log.i(TAG, "Check_Login_user: CURSOR IS NOT NULL");
cursor.moveToFirst();
String password = cursor.getString(USER_COL_PASSWORD);
String username = cursor.getString(USER_COL_NAME);
String email = cursor.getString(USER_COL_EMAIL);
Log.i(TAG, "Check_Login_user: DATA FETCHED FROM DB IS :\n"
+ "NAME: " + username + "\n"
+ "Email : " + email + "\n"
+ "Password : " + password + "\n"
);
Log.i(TAG, "Check_Login_user: MATCHING :" + username + " with " + UserName
+ " and " + password + " with " + UserPassword +"\n");
if (username.equals(UserName) && password.equals(UserPassword)) {
Log.i(TAG, "Check_Login_user: USER FOUND \n");
Current_active_user_id = cursor.getInt(USER_COL_ROW_ID);
Log.i(TAG, "Check_Login_user: CURRENT USER ID IS :" + Current_active_user_id + "\n");
} else {
Log.i(TAG, "Check_Login_user: INCORRECT PASSWORD");
Current_active_user_id = -2;
}
}else{
Log.i(TAG, "Check_Login_user: NO SUCH USERNAME");
Current_active_user_id = -4;
}
return Current_active_user_id;
}
//insert new group of the current user in the group table
public long insert_Row_group(String GroupName, int TotalBudget, int TotalMembers){
//set up contentValues to insert the data into the required DB
ContentValues contentValues = new ContentValues();
//feed data into the contentValues
contentValues.put(GROUP_KEY_NAME, GroupName);
contentValues.put(GROUP_KEY_TOTAL_BUDGET, TotalBudget);
contentValues.put(GROUP_KEY_TOTAL_MEMBERS, TotalMembers);
/*
insert the data stored in the contentValues into the DB_GROUP
The return statement will return the id of the newly entered user in the user table
this is the reason why the return type is long
*/
return db_writable.insert(DB_TABLE_GROUP, null, contentValues);
}
//insert new member of the current group in the member table
public long insert_Row_member(){
return -1;
}
//delete specific user in the user table
public boolean delete_Row_user(){
return true;
}
//delete specific group of the current user in the group table
public boolean delete_Row_group(){
return true;
}
//delete specific member in the group of the current user from the member table
public boolean delete_Row_member(){
return true;
}
//delete all the users from the user table
public void delete_all_users(){
}
//delete all the groups of the current user from the group table
public void delete_all_groups(){
}
//delete all the members in the current group of the active user from the member table
public void delete_all_members(){
}
//retrieve all the data present in the user table.
public Cursor getAll_users(){
Log.i(TAG, "getAll_users: ENTERED getAll_users");
Cursor cursor = db_readable.query(
DB_TABLE_USER,
USER_ALL_KEYS,
null,
null,
null,
null,
null,
null
);
if(cursor != null)
{ Log.i(TAG, "getAllRows_users: DATA FETCHED SUCCESSFULLY");
cursor.moveToFirst();
}
else {
Log.i(TAG, "getAllRows_users: NO DATA FOR USERS FETCHED");
}
return cursor;
}
//retrieve all the data present in the group table for the current user
//public Cursor getAllRows_groups(){
//}
//retrieve all the data present in the member table for the specific group of current user
//public Cursor getAllRows_members(){
//}
//Creating private DataBase Helper class to initialize the database
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//initialize user table
db.execSQL(DB_CREATE_QUERY_USER);
//initialize group table
db.execSQL(DB_CREATE_QUERY_GROUP);
//initialize member table
db.execSQL(DB_CREATE_QUERY_MEMBER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//if table columns are changed or updated, delete the previous version
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_USER);
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_GROUP);
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_MEMBER);
//and re-initialize the databases with updated parameters
onCreate(db);
}
}//End of DBHelper class
}//End Login_Signup_DB_adapter class
THIS IS THE LOG ERROR THAT I AM GETTING WHEN I CLICK ON THE "DISPLAY USERS" BUTTON.
05-20 08:37:20.413 1818-1818/? I/LOGIN: checkInDataBase: LOGIN USER EXISTS WITH ID :1
05-20 08:37:25.106 594-938/? I/WindowManager: Destroying surface Surface(name=com.rishabh.admin.bucomp/com.rishabh.admin.bucomp.MainActivity_Login) called by com.android.server.wm.WindowStateAnimator.destroySurface:2014 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:881 com.android.server.wm.WindowState.destroyOrSaveSurface:2073 com.android.server.wm.WindowManagerService.tryStartExitingAnimation:3017 com.android.server.wm.WindowManagerService.relayoutWindow:2897 com.android.server.wm.Session.relayout:215 android.view.IWindowSession$Stub.onTransact:286 com.android.server.wm.Session.onTransact:136
<LOG ERROR>
05-20 08:37:33.637 1818-1818/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rishabh.admin.bucomp, PID: 1818
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.rishabh.admin.bucomp.Login_Signup_DB_adapter.getAll_users()' on a null object reference
at com.rishabh.admin.bucomp.fragment_home_left.Fetch_user_data(fragment_home_left.java:72)
at com.rishabh.admin.bucomp.fragment_home_left.onClick(fragment_home_left.java:62)
at android.view.View.performClick(View.java:5609)
at android.view.View$PerformClick.run(View.java:22259)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
You have not initialized your db_adapter that's why db_adapter is null and you are calling a function of Login_Signup_DB_adapter class. So, you need to initialize db_adapter like this in onCreateView of fragment_home_left class
db_adapter = new Login_Signup_DB_adapter(this);
You have to instantiate the adapter. Try adding
db_adapter = new Login_Signup_DB_adapter(getContext())
in your Fragment onCreate() method

Getting error in the on create method for sqlite database

I am creating a trivia game for a class assignment. I initially wanted to store the questions with categories in a sqlite database. I'm strating with one table, though I want to add others for category, level, and users, but first wanted to get it working with just questions. The program compiles and installs into the emulator and the first part works fine. It's not until the app goes to create the database that I get an error. The error reads:
Caused by:
android.database.sqlite.SQLiteException: near "TABLEquestion": syntax error (code 1): , while compiling: CREATE TABLEquestion(questionIDINTEGER PRIMARY KEY,questionNameTEXT,optionATEXT,optionBTEXT,optionCTEXT,answerTEXT,questionLevelIDINTEGER,categoryIDINTEGER)
at android.database.sqlite
My code for the main activity, trivia question activity, question class, DBHelper class and the xml layout for the Trivia Question activity. Please note, the error occurs when the radio button is selected for a category, which launches the Trivia Question activity. (before adding the database, the launch worked without error). Also, I know I need to create methods for Updating and Deleting records, but wanted to get the database creation working first. I've looked at this for 2 days and cannot find the issue. Any assistance would be greatly appreciated.
CLASS QUESTION:
public class Question {
private Integer questionID;
private String questionName;
private String optionA;
private String optionB;
private String optionC;
private String answer;
private Integer questionLevelID;
private Integer categoryID;
public Question(){
//// TODO: 11/5/2016
}
public Question (Integer questionID, String questionName, String optionA,
String optionB, String optionC, String answer, Integer questionLevelID,
Integer catID){
this.questionID=questionID;
this.questionName=questionName;
this.optionA=optionA;
this.optionB=optionB;
this.optionC=optionC;
this.answer=answer;
this.questionLevelID=questionLevelID;
this.categoryID = catID;
}
public void setqID(Integer questionId){
this.questionID = questionId;
}
public void setqName(String questionName){
this.questionName=questionName;
}
public void setqOptA(String optionA){
this.optionA = optionA;
}
public void setqOptB(String optionB){
this.optionB = optionB;
}
public void setqOptC(String optionC){
this.optionC=optionC;
}
public void setqAns(String answer){
this.answer = answer;
}
public void setQLevel(Integer questionLevelID){
this.questionLevelID = questionLevelID;
}
public void setqcatID(Integer categoryID){
this.categoryID= categoryID;
}
public int getqID(){
return questionID;
}
public String getqName(){
return questionName;
}
public String getqOptA(){
return optionA;
}
public String getqOptB(){
return optionB;
}
public String getqOptC(){
return optionC;
}
public String getqAns(){
return answer;
}
public Integer getqLevel(){
return questionLevelID;
}
public Integer getqCatID(){
return categoryID;
}
}
MAIN ACTIVITY:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.util.Log;
import java.util.List;
import static android.R.attr.id;
public class EduTriviaMain extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_trivia_main);
}
public String onCheckedChanged(View view) {
boolean checked = ((RadioButton) view).isChecked();
String category = "";
switch (view.getId()) {
case R.id.englishRadioButton:
if (checked) {
category = "english";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.historyRadioButton:
if (checked) {
category = "history";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.mathRadioButton:
if (checked) {
category = "math";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
default:
break;
}
return category;
}
}
DBHelper Class:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DBHandler extends SQLiteOpenHelper{
//Database Version
private static final int DATABASE_VERSION=1;
//Database Name
private static final String DATABASE_NAME ="eduTrivia";
//table names
private static final String TABLE_QUESTION="question";
//question table column names
private static final String KEY_QUESTIONID = "questionID";
private static final String KEY_QUESTION="questionName";
private static final String KEY_OPTIONA="optionA";
private static final String KEY_OPTIONB="optionB";
private static final String KEY_OPTIONC="optionC";
private static final String KEY_ANSWER="answer";
private static final String KEY_LEVEL = "questionLevelID";
private static final String KEY_CATEGORYID="categoryID";
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE"
+ TABLE_QUESTION +"("
+ KEY_QUESTIONID +"INTEGER PRIMARY KEY,"
+ KEY_QUESTION + "TEXT,"
+ KEY_OPTIONA + "TEXT,"
+ KEY_OPTIONB + "TEXT,"
+ KEY_OPTIONC + "TEXT,"
+ KEY_ANSWER + "TEXT,"
+ KEY_LEVEL + "INTEGER,"
+ KEY_CATEGORYID + "INTEGER"+")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUESTION);
addQuestions();
}
private void addQuestions(){
Question q1 = new Question(1,"How do you write this number using words? 752",
"five hudnred sixty-two","seven hundred sixty-two", "seven hundred fifty-two",
"C",1,1);
Question q2 = new Question(2,"Round 5,764,438 to the nearest hundred thousand",
"6,200,000","5,800,000","5,700,000","B",1,1);
Question q3= new Question(3,"Which equation shows the associative property of addition",
"5+4=3+6","7+(4+3)=(7+4)+3", "0+8=8","B",1,1);
Question q4 = new Question(4,"Select the adjective in this sentence: Nina is a strong worker",
"Nina","strong","worker","B",1,2);
Question q5 = new Question (5,"Select the adjective in this sentence: The twon has three banks",
"The","town","three","C",1,2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists"+TABLE_QUESTION);
onCreate(db);
}
//constructor and getInstance() method
private static DBHandler mDBHANDLER;
public static synchronized DBHandler getInstance(Context context) {
if (mDBHANDLER==null){
mDBHANDLER=new DBHandler(context.getApplicationContext());
}
return mDBHANDLER;
}
public DBHandler(Context context){
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
public void addQuestion(Question question){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUESTIONID,question.getqID());
values.put(KEY_QUESTION,question.getqName());
values.put(KEY_OPTIONA,question.getqOptA());
values.put(KEY_OPTIONB,question.getqOptB());
values.put(KEY_OPTIONC,question.getqOptC());
values.put(KEY_ANSWER,question.getqAns());
values.put(KEY_LEVEL,question.getqLevel());
values.put(KEY_CATEGORYID,question.getqCatID());
db.insert(TABLE_QUESTION,null,values);
db.close();
}
//reading records
public Question getQuestion(int id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_QUESTION, new String[]{
KEY_QUESTIONID, KEY_QUESTION
},KEY_QUESTIONID + "=?",
new String[]{
String.valueOf(id)},null,null,null,null);
if (cursor !=null)
cursor.moveToFirst();
Question question = new Question(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2), cursor.getString(3),
cursor.getString(4),cursor.getString(5),Integer.parseInt(cursor.getString(6)),
Integer.parseInt(cursor.getString(7)));
return question;
}
public List<Question> getAllQuestions(){
//Select all questions query
List questionList = new ArrayList<Question>();
String selectAll = "SELECT * FROM "+TABLE_QUESTION;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectAll,null);
//loop through all rows and add to the list
if (cursor.moveToFirst()){
do{
Question question = new Question ();
question.setqID(Integer.parseInt(cursor.getString(0)));
question.setqName(cursor.getString(1));
question.setqOptA(cursor.getString(2));
question.setqOptB(cursor.getString(3));
question.setqOptC(cursor.getString(4));
question.setqAns(cursor.getString(5));
//adding to list
questionList.add(question);
}while (cursor.moveToNext());
}
return questionList;
}
}
TRIVIA QUESTION ACTIVITY:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.List;
import static android.R.id.list;
public class TriviaQuestion extends AppCompatActivity {
List<Question> questionList;
int score=0;
int questionID = 0;
Question currentQ;
TextView txtQuestion;
RadioButton rda,rdb,rdc;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trivia_question);
DBHandler db = new DBHandler(this);
questionList = db.getAllQuestions();
currentQ = questionList.get(questionID);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
setQuestionView();
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getqName());
rda.setText(currentQ.getqOptA());
rdb.setText(currentQ.getqOptB());
rdc.setText(currentQ.getqOptC());
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getqAns().equals(answer.getText())) {
score++;
}
currentQ = questionList.get(questionID);
setQuestionView();
}
});
}
}
TRIVIA QUESTION LAYOUT XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_trivia_question"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rasmussenandroid.sandra.edutrivia.TriviaQuestion">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.04" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="next" />
</LinearLayout>
</RelativeLayout>
The error tells you what the issue is - the SQL query is not constructed properly. There should be spaces between the individual terms - for example, CREATE TABLEquestion should be CREATE TABLE question.
Try the following line for CREATE_TABLE_QUESTION :
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE "
+ TABLE_QUESTION +" ( "
+ KEY_QUESTIONID +" INTEGER PRIMARY KEY, "
+ KEY_QUESTION + " TEXT , "
+ KEY_OPTIONA + " TEXT, "
+ KEY_OPTIONB + " TEXT, "
+ KEY_OPTIONC + " TEXT, "
+ KEY_ANSWER + " TEXT, "
+ KEY_LEVEL + " INTEGER, "
+ KEY_CATEGORYID + " INTEGER "+")";

ListView duplicates items everytime I restart the activity

I feel like this is a really simple fix but I am new the android and sqlite in general. I have a array that takes data from a database and then shows them in a list. However every time I restart the app the list adds the items once again into the list. How can I make it not do this?
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.assignmenttracker.MySQLiteHelper;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
private ListView ListView;
private Button addbutton;
public final static String ID_EXTRA="com.example.assignmenttracker._ID";
public static ArrayList<String> ArrayofName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.addbutton = (Button)this.findViewById(R.id.button1);
this.addbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this, AddAssign.class);
startActivity(intent);
}
});
}
private void populateListView() {
MySQLiteHelper db = new MySQLiteHelper(this);
List<tasklist> contacts = db.getSometasklist();
for (tasklist cn : contacts) {
Log.d("Reading: ", "Reading all contacts..");
String log = "Id: "+cn.getID()+" ,Task: " + cn.getTask() + " ,Date: " + cn.getDate() + " ,Status: " + cn.getStatus();
Log.d("Name: ", log);
}
ListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
ListView.setAdapter(adapter);
ListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(MainActivity.this, ViewAssign.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);}
});
}
#Override
public void onResume() {
super.onResume();
populateListView();
}
}
here is the code of mysqlitehelper
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Contacts Table Columns names
private static final String TABLE_CONTACTS = "tasklist1";
private static final String KEY_ID = "id";
private static final String KEY_TASK = "task";
private static final String KEY_DESC = "desc";
private static final String KEY_MOD = "module";
private static final String KEY_DATE = "date";
private static final String KEY_TYPE = "type";
private static final String KEY_STATUS = "status";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "tasklist1";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TASKLIST_TABLE = "CREATE TABLE tasklist1 ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"task TEXT, "+
"desc TEXT, "+
"module TEXT, "+
"date TEXT, "+
"type TEXT, "+
"status INTEGER )";
db.execSQL(CREATE_TASKLIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older task list table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// create fresh task list table
this.onCreate(db);
}
public void insertTask(tasklist tasklist){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, tasklist.getTask());
values.put(KEY_DESC, tasklist.getDesc());
values.put(KEY_MOD, tasklist.getModule());
values.put(KEY_DATE, tasklist.getDate());
values.put(KEY_TYPE, tasklist.getType());
values.put(KEY_STATUS, tasklist.getStatus());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public List<tasklist> getAlltasklist(int passedid) {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS +
" where id = " + passedid;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDesc(cursor.getString(2));
contact.setModule(cursor.getString(3));
contact.setDate(cursor.getString(4));
contact.setType(cursor.getString(5));
contact.setStatus(cursor.getInt(6));
String name = cursor.getString(1);
String desc =cursor.getString(2);
String module =cursor.getString(3);
String date = cursor.getString(4);
String type = cursor.getString(5);
int status = cursor.getInt(6);
ViewAssign.task= name;
ViewAssign.desc=desc;
ViewAssign.module=module;
ViewAssign.date=date;
ViewAssign.type=type;
ViewAssign.status=status;
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public List<tasklist> getSometasklist() {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDate(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(4);
MainActivity.ArrayofName.add(name);
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public void deleteTask(long row) {
// Deletes a row given its rowId, but I want to be able to pass
// in the name of the KEY_NAME and have it delete that row.
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=" + row, null);
db.close();
}
}
I suspect the culprint is this:
public static ArrayList<String> ArrayofName = new ArrayList<String>();
It is a static variable, meaning that in some circumstances, it will STILL have the objects you added on app first run when you run it second time.
Possible solutions:
remove "static" keyword, or
clear ArrayOfName before populating it, eg. ArrayOfName.clear()
I know I am late but maybe it will help someone else.
You need to split ArrayList into two parts
Place the following code in MainActivity
public static ArrayList<String> ArrayofName;
And place the following in onCreate() OR onResume() method
ArrayofName = new ArrayList<String>();

saving image in sqlite db using a save button

I'm a newbie in developing an android app and I am currently developing cooking application. I want to add a new recipe to my db with recipe name, ingredients, procedures, category, notes and photo. But the problem is when I add photo from camera or gallery, it stop working and I want to view the image taken to an imageview and save it to db using a save button. But please help me. I don't know what to do with my project.
MY DBAdapter
package com.elasandesu.quickeasykitchenv3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_RNAME = "rname";
public static final String KEY_RCAT = "rcat";
public static final String KEY_RING = "ring";
public static final String KEY_RSTEPS = "rsteps";
public static final String KEY_RNOTE = "rnote";
public static final String KEY_RPHOTO = "rphoto";
//public static final String KEY_RPHOTONME = "rphotornme";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_RNAME = 1;
public static final int COL_RCAT = 2;
public static final int COL_RING = 3;
public static final int COL_RSTEPS = 4;
public static final int COL_RNOTE = 5;
public static final int COL_RPHOTO = 6;
//public static final int COL_RPHOTONME =7;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_RNAME, KEY_RCAT, KEY_RING, KEY_RSTEPS, KEY_RNOTE, KEY_RPHOTO};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Quick.sqlite";
public static final String DATABASE_TABLE = "recipe";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 5;
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_RNAME + " TEXT,"
+ KEY_RCAT + " TEXT," + KEY_RING+ " TEXT," + KEY_RSTEPS + " TEXT,"
+ KEY_RNOTE + " TEXT," + KEY_RPHOTO + " BLOB" + ")";
db.execSQL(CREATE_RECIPE_TABLE);
}
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_RNAME, rName);
initialValues.put(KEY_RCAT, rCat);
initialValues.put(KEY_RING, rIng);
initialValues.put(KEY_RSTEPS, rSteps);
initialValues.put(KEY_RNOTE, rNote);
//initialValues.put(KEY_RPHOTO, rPhoto);
//initialValues.put(KEY_RPHOTONME, rPhotonme);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//Get specific row by category
public Cursor getCateg (String categ) throws SQLException {
String where = "SELECT * FROM recipe where rcat=\""+categ+"\"";
Cursor c = db.rawQuery(where, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//KEY_RCAT + " = \'" + categ + " \'";
//"select * from contacts where id="+id+"", null
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_RNAME, rName);
newValues.put(KEY_RCAT, rCat);
newValues.put(KEY_RING, rIng);
newValues.put(KEY_RSTEPS, rSteps);
newValues.put(KEY_RNOTE, rNote);
//newValues.put(KEY_RPHOTO, rPhoto);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteAssetHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
}
Activity Code
package com.elasandesu.quickeasykitchenv3;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Addrecipe extends Activity implements OnItemSelectedListener{
String[] cat = {"BEEF","CHICKEN",
"PORK", "FISH", "VEGETABLES"};
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
private String selectedImagePath;
String DB_NAME = Environment.getExternalStorageDirectory() + "/Quick.sqlite";
String TABLE_NAME = "recipe";
ImageView recphoto;
DBAdapter db;
EditText recname, recing, recsteps, recnote;
Spinner spinner1;
TextView category;
Button save, reset, upload;
public static String rcat = " ";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addrecipe);
category = (TextView) findViewById(R.id.categorytxtview);
spinner1 = (Spinner) findViewById(R.id.categorysp);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cat);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter_state);
spinner1.setOnItemSelectedListener(this);
save = (Button) findViewById(R.id.savebtn);
reset = (Button) findViewById(R.id.resetbtn);
recname = (EditText) findViewById(R.id.recipename);
recing = (EditText) findViewById(R.id.ingredient);
recnote = (EditText) findViewById(R.id.note);
recsteps = (EditText) findViewById(R.id.procedure);
recphoto= (ImageView) findViewById(R.id.image);
openDB();
final String[] option = new String[] { "Take from Camera", "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
Button addImage = (Button) findViewById(R.id.uploadbtn);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
//insert activity here :D
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras= data.getExtras();
if (extras != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage.compress(CompressFormat.PNG, 0, stream);
byte[] bytes = stream.toByteArray();
recphoto.setImageBitmap(selectedImage);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
recphoto.setImageURI(selectedImageUri);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("crop", "true");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
db = new DBAdapter(this);
db.open();
}
private void closeDB() {
db.close();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinner1.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void saveHasBeenClicked (View v) {
String rName = recname.getText().toString();
String rIng = recing.getText().toString();
String rSteps =recsteps.getText().toString();
String rNote = recnote.getText().toString();
String rCat = (String) spinner1.getSelectedItem();
long newId = db.insertRow(rName,"\n"+ rCat," \n "+ rIng," \n" + rSteps, rNote);
Cursor cursor = db.getRow(newId);
displayRecordSet(cursor);
Intent evilIntent = new Intent(Addrecipe.this, Selected.class);
startActivity(evilIntent);
}
public void onClick_ClearAll(View v) {
db.deleteAll();
Toast.makeText(getBaseContext(), "Cleared ", Toast.LENGTH_LONG).show();
}
// Display an entire record set to the screen.
private void displayRecordSet(Cursor cursor) {
String message = "";
// populate the message from the cursor
// Reset cursor to start, checking to see if there's data:
if (cursor.moveToFirst()) {
do {
// Process the data:
int id = cursor.getInt(DBAdapter.COL_ROWID);
String rName = cursor.getString(DBAdapter.COL_RNAME);
String rCat = cursor.getString(DBAdapter.COL_RCAT);
String rIng = cursor.getString(DBAdapter.COL_RING);
String rSteps = cursor.getString(DBAdapter.COL_RSTEPS);
String rNote = cursor.getString(DBAdapter.COL_RNOTE);
// Append data to the message:
message += "id=" + id
+", Recipe Name : " + rName
+", Category : " + rCat
+", Ingredients : " + rIng
+", Procedure: " + rSteps
+", Note: " + rNote
+"\n";
} while(cursor.moveToNext());
Toast.makeText(getBaseContext(), "Save Has Been Clicked "+ message, Toast.LENGTH_LONG).show();
}
// Close the cursor to avoid a resource leak.
cursor.close();
}
}
And the XML file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/clr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/nb"
android:onClick="displayClicked"
android:screenOrientation="landscape"
tools:ignore="HardcodedText" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1462dp" >
<EditText
android:id="#+id/recipename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/recipenametxtview"
android:layout_alignBottom="#+id/recipenametxtview"
android:layout_alignParentRight="true"
android:layout_marginRight="70dp"
android:ems="10"
android:hint="Type the Recipe Name"
tools:ignore="TextFields" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/categorytxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recipenametxtview"
android:layout_below="#+id/recipename"
android:layout_marginTop="50dp"
android:text="Category:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/ingtxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/categorytxtview"
android:layout_below="#+id/categorysp"
android:layout_marginTop="42dp"
android:text="Ingredients:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/categorysp"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignLeft="#+id/recipename"
android:layout_alignRight="#+id/recipename"
android:layout_alignTop="#+id/categorytxtview" />
<TextView
android:id="#+id/notetxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="253dp"
android:text="Note:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/ingredient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingtxtview"
android:layout_alignRight="#+id/categorysp"
android:layout_below="#+id/ingtxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type Here the Ingredients : e.g. 1 kilo of Flour"
android:inputType="text"
android:singleLine="false"
tools:ignore="TextFields" />
<EditText
android:id="#+id/procedure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_alignRight="#+id/ingredient"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type in this format 1.) procedure 1 [newline] 2.) procedure 2"
tools:ignore="TextFields" />
<EditText
android:id="#+id/note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/notetxtview"
android:layout_alignRight="#+id/procedure"
android:layout_below="#+id/notetxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Includes information, cautions and other health information"
tools:ignore="TextFields" />
<TextView
android:id="#+id/recipenametxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/itemRname"
android:layout_marginLeft="62dp"
android:layout_marginTop="67dp"
android:text="Recipe Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phototxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/note"
android:layout_below="#+id/note"
android:layout_marginTop="101dp"
android:text="Photo:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/proceduretxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingredient"
android:layout_below="#+id/ingredient"
android:layout_marginTop="172dp"
android:text="Procedure:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/uploadbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/phototxtview"
android:layout_alignBottom="#+id/phototxtview"
android:layout_toRightOf="#+id/ingtxtview"
android:text="Upload Photo" />
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_below="#+id/uploadbtn"
android:layout_marginTop="42dp"/>
<Button
android:id="#+id/resetbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/savebtn"
android:layout_alignBottom="#+id/savebtn"
android:layout_alignRight="#+id/note"
android:layout_marginRight="55dp"
android:onClick="onClick_ClearAll()"
android:text="Reset" />
<Button
android:id="#+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/uploadbtn"
android:layout_below="#+id/image"
android:layout_marginTop="56dp"
android:onClick="saveHasBeenClicked"
android:text="Save" />
</RelativeLayout>
</ScrollView>
please help me.. it will be a great help.

no such column: KEY_PUBNAME

Im making an app which stores data in an SQLite database. I want to be able to add, edit and delete data from this database. I can app to it no problem. I am currently working on trying to delete from the database but I keep getting the same error.
(1) no such column: KEY_PUBNAME
Here is my Java file:
package com.example.beer_budget3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
db.open();
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
Here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
And here is my database adapter:
package com.example.beer_budget3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not
null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;
// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
KEY_PUBNAME is clearly declared in the database adapter.
Any help would be great.
If you see your DatabaseHelper, you've defined following:
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
The keyname you've mentioned is KEY_PUBNAME. However where you've created the table, the keyname you've defined is Pub_Name. Over here:
public static final String KEY_PUBNAME = "Pub_Name";
That's why its not found. KEY_PUBNAME is the variable you've declared and not the name of the column. You may want to try to change it in db.delete statement.

Categories