Getting an NullPointerException while trying to create a SQL Lite database - Android - java

I'm new to android and I am learning to create 'SQLite Database.When I execute the application I am getting theNullPointerException` error. can someone help me to fix this. Thanks
Here is my code.
Add Schedule Class
public class Addschedule extends ActionBarActivity {
ScheduleAdapater schedulehelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addschedule);
schedulehelper = new ScheduleAdapater(this);
Button bt = (Button) findViewById(R.id.btn_add_schedule);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addschedule();
}
});
}
public void addschedule(){
EditText et_id_1 = (EditText) findViewById(R.id.et_id);
EditText et_name_1 = (EditText) findViewById(R.id.et_name);
EditText et_date_1 = (EditText) findViewById(R.id.et_date);
int sch_id = Integer.parseInt(String.valueOf(et_id_1.getText()));
String name = et_name_1.getText().toString();
String date = et_date_1.getText().toString();
long id = schedulehelper.InsertData(sch_id, name, date);
if(id<0){
Message.message(this, "Unsuccessful insert");
}else{
Message.message(this, "successful insert");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_addschedule, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Schedule Adapter Class
public class ScheduleAdapater {
scheduleHelper sch_helper;
public ScheduleAdapater(Context context){sch_helper = new scheduleHelper(context); }
public long InsertData(Integer id, String name, String date){
SQLiteDatabase db = sch_helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(scheduleHelper.SCH_ID, id);
contentValues.put(scheduleHelper.SCH_NAME, name);
contentValues.put(scheduleHelper.SCH_DATE, date);
long result_id = db.insert(scheduleHelper.TABLE_NAME, null, contentValues);
return result_id;
}
static class scheduleHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "certisagent";
private static final String TABLE_NAME = "schedule";
private static final int DATABASE_VERSION = 3;
private static final String SCH_ID="schedule_id";
private static final String SCH_NAME = "schedule_name";
private static final String SCH_DATE="schedule_date";
private Context context;
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+SCH_ID+" " +
"INTEGER PRIMARY KEY, "+SCH_NAME+" VARCHAR(255), "+SCH_DATE+" VARCHAR(50));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME+";";
public scheduleHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Message.message(context, "Oncreate called");
db.execSQL(CREATE_TABLE);
}catch (SQLException e){
Message.message(context, ""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "onupgrade called");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (SQLException e){
Message.message(context, ""+e);
}
}
}
}
Message class
public class Message {
public static void message(Context context, String message){
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
Error Stack
07-03 12:27:35.630 4482-4482/lk.db.learn.learndb E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: lk.db.learn.learndb, PID: 4482
java.lang.NullPointerException
at android.widget.Toast.<init>(Toast.java:106)
at android.widget.Toast.makeText(Toast.java:264)
at lk.db.learn.learndb.Message.message(Message.java:11)
at lk.db.learn.learndb.ScheduleAdapater$scheduleHelper.onUpgrade(ScheduleAdapater.java:66)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at lk.db.learn.learndb.ScheduleAdapater.InsertData(ScheduleAdapater.java:21)
at lk.db.learn.learndb.Addschedule.addschedule(Addschedule.java:48)
at lk.db.learn.learndb.Addschedule$1.onClick(Addschedule.java:28)
at android.view.View.performClick(View.java:4496)
at android.view.View$PerformClick.run(View.java:18603)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
can someone help me to fix this.Thank you.

context=null at
Message.message(context, "Oncreate called");
So initialized it before used
public scheduleHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
}
in scheduleHelper class

Create a global variable in ScheduleAdapater class
private Context mContext;
And pass context to your ScheduleAdapater constructor
public ScheduleAdapater(Context context){
this.mContext = context;
}

Related

getWritableDatabase() causing nullPointerException

I want to open my database with SQLite. But when attempting to take data from a TextInputEditText and put it into the database it throws NPE at db = this.getWritableDatabase();
Seems that most of the time this is caused by the context being null. But it is not null and I checked it with debugger. (myDB = new DatabaseHelper(this);)
(I have tried all other questions about this problem and my situation must be different because they did not help.)
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
TextInputEditText inputEmail;
TextInputEditText inputPass;
Button btn_login;
Button btn_signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myDB = new DatabaseHelper(this);
} catch (Exception e) {
System.out.print("Exception occurred");
}
btn_signup = findViewById(R.id.btn_signup);
btn_login = findViewById(R.id.btn_login);
addData();
}
public void addData() {
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEmail = findViewById(R.id.editTextEmail);
inputPass = findViewById(R.id.editTextPass);
//try {
myDB.insertData(inputEmail.getText().toString(),
inputPass.getText().toString());
Toast.makeText(MainActivity.this, "Data Inserted",
Toast.LENGTH_LONG).show();
// } catch (Exception e) {
// e.printStackTrace();
// }
}
});
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Login_android.db";
public static final String TABLE_NAME = "login_table.db";
public static final String COL1 = "ID";
public static final String COL2 = "EMAIL";
public static final String COL3 = "PASSWORD";
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 +" (ID INTEGER PRIMARY KEY
AUTOINCREMENT, EMAIL TEXT, PASSWORD 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 email, String password) {
SQLiteDatabase db = null;
try {
db = this.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//db.isOpen();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, email);
contentValues.put(COL3, password);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
}
Exception
12-06 23:39:12.799 26304-26304/com.example.ryan.temporaryname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ryan.temporaryname, PID: 26304
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
at com.example.ryan.temporaryname.DatabaseHelper.insertData(DatabaseHelper.java:45)
at com.example.ryan.temporaryname.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I think the problem is about TABLE_NAME - "login_table.db" suggests a table named "db" in a database named "login_table", which does not exist, and a null database object is returned.
Please try to change the name.
i think you should ( if this is not a test sqlite app) create a singleton by create a App() class and initialize the database in there.Try to firgure out your problem too

My application crashes after I try to insert an Item into my database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I can open my Datenbase but if I try to insert an item my application crashes.
Insert the item only to my ListView works.
I create a new Object in another Activity and take the Values in an Intent.
But when I start the intent and go back to the Main/List_page Activity my App crashes. Without the Database, the application runs.
Heres my codes: ReceptListAdapter.java:
public class ReceptListDatabase {
private static final String DATABASE_NAME = "receptlist.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_TABLE = "receptlistitems";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KATEGORY = "kategory";
public static final String KEY_INGREDIENTS = "ingredients";
public static final String KEY_DIRECTIONS = "ingredients";
public static final int COLUMN_NAME_INDEX = 1;
public static final int COLUMN_KATEGORY_INDEX = 2;
public static final int COLUMN_INGREDIENTS_INDEX = 3;
public static final int COLUMN_DIRECTIONS_INDEX = 4;
private ReceptDBOpenHelper dbHelper;
private SQLiteDatabase DB;
public ReceptListDatabase(Context context) {
dbHelper = new ReceptDBOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public void open() throws SQLException {
try {
db = dbHelper.getWritableDatabase();
} catch (SQLException e) {
db = dbHelper.getReadableDatabase();
}
}
public void close() {
db.close();
}
public long insertReceptItem(ListItem item) {
ContentValues itemValues = new ContentValues();
itemValues.put(KEY_NAME, item.getName());
itemValues.put(KEY_KATEGORY,item.getKategory());
itemValues.put(KEY_INGREDIENTS, item.getIngredients());
itemValues.put(KEY_DIRECTIONS, item.getDirection());
return db.insert(DATABASE_TABLE, null, itemValues);
}
public void removeReceptItem(ListItem item) {
String toDelete = KEY_NAME + "=?";
String[] deleteArguments = new String[]{item.getName()};
db.delete(DATABASE_TABLE, toDelete, deleteArguments);
}
public ArrayList<ListItem> getAllReceptItems() {
ArrayList<ListItem> items = new ArrayList<ListItem>();
Cursor cursor = db.query(DATABASE_TABLE, new String[] { KEY_ID,
KEY_NAME, KEY_KATEGORY, KEY_INGREDIENTS, KEY_DIRECTIONS, null}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(COLUMN_NAME_INDEX);
String kategory = cursor.getString(COLUMN_KATEGORY_INDEX);
String ingredients = cursor.getString(COLUMN_INGREDIENTS_INDEX);
String directions = cursor.getString(COLUMN_DIRECTIONS_INDEX);
items.add(new ListItem(name, kategory, ingredients, directions, null));
} while (cursor.moveToNext());
}
return items;
}
private class ReceptDBOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null, " + KEY_KATEGORY
+ " text, " + KEY_INGREDIENTS
+ " text not null, " + KEY_DIRECTIONS
+ " text not null);";
public ReceptDBOpenHelper(Context c, String dbname,
SQLiteDatabase.CursorFactory factory, int version) {
super(c, dbname, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
And my Main Activity:
public class List_Page extends Activity {
private ListViewAdapter adapter;
private ArrayList<ListItem> itemList;
private ListView list;
private DatabaseAdapter receptDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setupButton();
setupListView();
addObject();
setupDatabase();
}
private void setupDatabase() {
receptDB = new DatabaseAdapter(this);
receptDB.open();
}
private void setupButton() {
Button addItemButton = (Button) findViewById(R.id.addItemButton);
addItemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked();
}
});
}
private void buttonClicked() {
//get EditText
Intent newItemIntent = new Intent(List_Page.this, Add_Object.class);
startActivity(newItemIntent);
finish();
}
private void setupListView() {
itemList = new ArrayList<ListItem>();
adapter = new ListViewAdapter(List_Page.this, itemList);
list = (ListView) findViewById(R.id.listItem);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
//fehler bei removeTaskAtPosition(position);
return true;
}
});
View header = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_list_item, null);
list.addHeaderView(header);
list.setAdapter(adapter);
}
private void addObject(){
Intent intent = getIntent();
if (intent.hasExtra(Constants.KEY_RECEPT_NAME)) {
String name = intent.getExtras().getString(Constants.KEY_RECEPT_NAME);
String kategory = intent.getExtras().getString(Constants.KEY_KATEGORY);
String ingredients = intent.getExtras().getString(Constants.KEY_INGREDIENTS);
String directions = intent.getExtras().getString(Constants.KEY_DIRECTIONS);
Bitmap image = (Bitmap) intent.getParcelableExtra(Constants.KEY_IMAGE);
ListItem newObject = new ListItem(name,kategory,ingredients,directions, image);
itemList.add(newObject);
receptDB.insertReceptItem(newObject);
//refreshArrayList();
}
}
private void refreshArrayList() {
ArrayList tempList = receptDB.getAllReceptItems();
itemList.clear();
itemList.addAll(tempList);
adapter.notifyDataSetChanged();
}
private void removeTaskAtPosition(int position) {
if (itemList.get(position) != null) {
receptDB.removeReceptItem(itemList.get(position));
refreshArrayList();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
receptDB.close();
}
}
Logcat:
08-12 15:37:00.743 22879-22879/de.ur.mi.android.excercises.starter E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.ur.mi.android.excercises.starter, PID: 22879
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.ur.mi.android.excercises.starter/de.ur.mi.android.excercises.starter.List_Page}: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
at de.ur.mi.android.excercises.starter.List_Page.addObject(List_Page.java:99)
at de.ur.mi.android.excercises.starter.List_Page.onCreate(List_Page.java:40)
at android.app.Activity.performCreate(Activity.java:6720)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:241) 
at android.app.ActivityThread.main(ActivityThread.java:6274) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
In your Activity's onCreate you are calling addObject() before calling setupDatabase(). Only inside setupDatabase() you are initialising receptDB instance.
But you are accessing that receptDb inside addObject() method.
receptDB.insertReceptItem(newObject);
So during that time, your receptDB has null reference and so you are getting NullPointerException.
So swap the below two lines from,
addObject();
setupDatabase();
to this:
setupDatabase();
addObject();

How to view all data from database?

This is my Database helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="assignment.db";
public static final String TABLE_NAME="assignment_data";
public static final int DATABASE_VERSION=1;
public static final String COL_1="ID";
public static final String COL_2="ASSIGNMENT_NAME";
public static final String COL_3="SUBMISSION_DATE";
public static final String COL_4="INFORMATION";
public static final String COL_5="REMARKS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create="create table "+TABLE_NAME+"("+COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_2+" TEXT NOT NULL,"+COL_3+" TEXT NOT NULL,"+COL_4+" TEXT NOT NULL,"+COL_5+" TEXT NOT NULL"+")";
db.execSQL(create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String upgrade="Drop table if exists "+TABLE_NAME;
db.execSQL(upgrade);
onCreate(db);
}
public boolean addAssignment(Assignment x){
SQLiteDatabase myDB=this.getWritableDatabase();
ContentValues content=new ContentValues();
content.put(COL_2,x.getName());
content.put(COL_3,x.getDate());
content.put(COL_4,x.getInfo());
content.put(COL_5,x.getRemarks());
long result=myDB.insert(TABLE_NAME,null,content);
if(result == -1){
return false;
}
else {
return true;
}
}
public Cursor viewAll(){
SQLiteDatabase MyDB=this.getReadableDatabase();
Cursor res=myDB.rawQuery("SELECT * FROM "+DatabaseHelper.TABLE_NAME,null);
return res;
}
/*public Cursor view(){
Cursor cursor=myDB.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID=?",new String[]{COL_1+""});
return cursor;
}*/
}
This is my View class:
public class View extends Activity {
Button viewAll,show;
EditText id;
DatabaseHelper dbHelper;
int id1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
viewAll = (Button)findViewById(R.id.viewAll);
show = (Button)findViewById(R.id.show);
id = (EditText)findViewById(R.id.id);
loadData();
//showData();
}
public void loadData(){
viewAll.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
Cursor cursor = dbHelper.viewAll();
if(cursor.getCount() == 0){
Toast.makeText(getApplicationContext(),"No Data for any Assignment found!",Toast.LENGTH_SHORT).show();
}
StringBuffer s = new StringBuffer("");
while(cursor.moveToNext()){
s.append("ID:"+cursor.getString(0)+"\n");
s.append("ASSIGNMENT NAME:"+cursor.getString(1)+"\n");
s.append("SUBMISSION DATE:"+cursor.getString(2)+"\n");
s.append("INFORMATION:"+cursor.getString(3)+"\n");
s.append("REMARKS:"+cursor.getString(4)+"\n\n");
}
showMessage("ASSIGNMENT DETAILS:",s.toString());
}
});
}
/*public void showData(){
show.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
id1=Integer.parseInt(id.getText().toString());
Cursor m=dbHelper.view(id1);
if(m.getCount()==0){
Toast.makeText(View.this,"No Data for the Assignment found!",Toast.LENGTH_SHORT).show();
}
StringBuffer sb= new StringBuffer();
while(m.moveToNext()){
sb.append("ID:"+m.getString(0)+"\n");
sb.append("ASSIGNMENT NAME:"+m.getString(1)+"\n");
sb.append("SUBMISSION DATE:"+m.getString(2)+"\n");
sb.append("INFORMATION:"+m.getString(3)+"\n");
sb.append("REMARKS:"+m.getString(4)+"\n\n");
}
showMessage("ASSIGNMENT DETAILS:",sb.toString());
}
});
}*/
public void showMessage(String title,String mess){
AlertDialog.Builder x=new AlertDialog.Builder(View.this);
x.setCancelable(true);
x.setTitle(title);
x.setMessage(mess);
x.show();
}
}
And This is the error I get:
07-10 08:51:45.497 27027-27027/com.dutt.rishabh.assignmentbuddy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dutt.rishabh.assignmentbuddy, PID: 27027
java.lang.NullPointerException
at com.dutt.rishabh.assignmentbuddy.View$1.onClick(View.java:36)
at android.view.View.performClick(View.java:4482)
at android.view.View$PerformClick.run(View.java:18787)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
I don't see your DatabaseHelper instance (dbHelper) getting initialized anywhere.
You need to initialize dbHelper before fetching all the records something like this:
dbHelper = new DatabaseHelper(this);
In your onClick method before entering the while loop add following line:
cursor.moveToFirst();
Then read through the cursor. If this doesn't solve your problem please upload whole LogCat messages
call cursor.moveToPrevious() before while(cursor.moveToNext())

how to get data from android database into an arraylist

I'm very new at android programming and this is my first question on stack overflow ever. I am having trouble understanding where i have gone wrong in my code implementation. I'm trying to store data in a database and then extract it into an arraylist.
This is the class where i add data into the database in the button onclicklistener:
public class KarmaDescription extends AppCompatActivity {
Button button;
TasksDBHandler dbHandler;
int tId = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_karma_desc2min);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Overview");
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyTasksGS myTask = new MyTasksGS(tId, "New Task Title", 2);
dbHandler.addTask(myTask);
Toast.makeText(KarmaDescription.this, "Task Added", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
This is the class which manages the database:
public class TasksDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "tasks.db";
public static final String TABLE_TASKS = "tasks";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TASKNAME = "taskname";
public static final String COLUMN_DAYSLEFT = "daysleft";
public TasksDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TASKS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_TASKNAME + " TEXT," +
COLUMN_DAYSLEFT + " INTEGER" +
")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
onCreate(db);
}
//Add a new row to the database
public void addTask(MyTasksGS myTask) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, myTask.getId());
values.put(COLUMN_TASKNAME, myTask.getTitle());
values.put(COLUMN_DAYSLEFT, myTask.getDaysRemaining());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_TASKS, null, values);
db.close();
}
//Delete row from the database
public void deleteTask(String taskID) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_TASKS + " WHERE " + COLUMN_ID + "=\"" + taskID + "\";");
}
//To put data into an arraylist
public List<MyTasksGS> getDataFromDB()
{
int id, daysRemaining;
String title;
List<MyTasksGS> tasksList = new ArrayList<MyTasksGS>();
String query = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
while (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
title = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TASKNAME));
daysRemaining = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_DAYSLEFT));
MyTasksGS myTask = new MyTasksGS(id, title, daysRemaining);
tasksList.add(myTask);
}
return tasksList;
}
}
I'm trying to copy the arraylist data which is returned from the above class(using getDataFromDB function) into myTaskList here and im getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.prateek.karma.TasksDBHandler.getDataFromDB()' on a null object reference
public class MyTasksFragment extends Fragment {
Button taskComplete;
RecyclerView RVMyTasks;
static MyTasksAdapter mtAdapter;
List<MyTasksGS> myTaskList = new ArrayList<>();
TasksDBHandler dbHandler;
public MyTasksFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_tasks, container, false);
taskComplete = (Button) view.findViewById(R.id.taskComplete);
RVMyTasks = (RecyclerView) view.findViewById(R.id.RVMyTasks);
mtAdapter = new MyTasksAdapter(myTaskList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
RVMyTasks.setLayoutManager(mLayoutManager);
RVMyTasks.setItemAnimator(new DefaultItemAnimator());
RVMyTasks.setAdapter(mtAdapter);
myTaskList = dbHandler.getDataFromDB();
mtAdapter.notifyDataSetChanged();
return view;
}
}
And this is the MyTasksGS class:
public class MyTasksGS {
String title;
int daysRemaining;
int id;
public MyTasksGS() {
}
public MyTasksGS(int id, String title, int daysRemaining) {
this.title = title;
this.daysRemaining = daysRemaining;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getDaysRemaining() {
return daysRemaining;
}
public void setDaysRemaining(int daysRemaining) {
this.daysRemaining = daysRemaining;
}
}
I may have made a very silly mistake somewhere but im not able to find it. Any help is appreciated
You need to instantiate the dbHandler, you are trying to use it without a valid instance. It causes the NullPointerException.
In your on onCreateView
before myTaskList = dbHandler.getDataFromDB();
add : dbHandler = new TasksDBHandler(getActivity());
use your class property DATABASE_NAME and DATABASE_VERSION instead of pass in constructor.
Change your TaskDBHandler constructor like this
public TasksDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

How can I add a delete function to my Sqlite Database?

I am building a training log that uses an sqlite database to save what the user inputs. Currently, I only have an add method that appends to the database, but am unsure as to how to create a delete method that removes the row created. The user data is initially created and added in TrainingLogCreate (class), which accesses DBAdapter's (Class) add method. What can I add to my remove method in DBAdapter to be able to remove a user entry?
TrainingLogCreate:
public class TrainingLogCreate extends AppCompatActivity {
EditText nameTxt;
EditText posTxt;
Button savebtn;
Context context = this;
public TrainingLogCreate() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_log_create);
savebtn = (Button) findViewById(R.id.saveButton);
nameTxt = (EditText) findViewById(R.id.exercizeActivity);
posTxt = (EditText) findViewById(R.id.exercizeDetails);
final DBAdapter db = new DBAdapter(this);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String datetime;
try {
Date date = new Date();
datetime = dateFormat.format(date);
} finally {
}
final String dateTxt = datetime;
savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//OPEN
db.openDB();
//INSERT
long result = db.add(nameTxt.getText().toString(), posTxt.getText().toString(), dateTxt.toString());
if (result > 0) {
nameTxt.setText("");
posTxt.setText("");
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
//CLOSE DB
db.close();
//Open Fragment
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.training_create_menu, menu);
getActionBar().show();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_save:
//add save functionality
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DBAdapter:
public class DBAdapter {
//COLUMNS
static final String ROWID="id";
static final String NAME = "name";
static final String POSITION = "position";
static final String DATE = "date";
//DB PROPERTIES
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL,position TEXT NOT NULL,date TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(FragmentActivity ctx) {
// TODO Auto-generated constructor stub
this.c=ctx;
helper=new DBHelper(c);
}
// INNER HELPER DB CLASS
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context ) {
super(context, DBNAME, null, DBVERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(CREATE_TB);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("DBAdapetr","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
// OPEN THE DB
public DBAdapter openDB()
{
try
{
db=helper.getWritableDatabase();
}catch(SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
//CLOSE THE DB
public void close()
{
helper.close();
}
//INSERT INTO TABLE
public long add(String name,String pos, String date)
{
try
{
ContentValues cv=new ContentValues();
cv.put(NAME, name);
cv.put(POSITION, pos);
cv.put(DATE, date);
return db.insert(TBNAME, ROWID, cv);
}catch(SQLException e)
{
e.printStackTrace();
}
return 0;
}
//REMOVE FROM TABLE
public long remove(String name)
{
}
//GET ALL VALUES
public Cursor getAllNames()
{
String[] columns={ROWID,NAME,POSITION,DATE};
return db.query(TBNAME, columns, null, null, null, null, null);
}
}
You can have a delete method like this
public void deleteInterestId(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TIMEKEEPER, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You have to pass the id which you want to delete. You have to customize this method a bit but it will give you an idea
And the most important thing for delete is that you have to also create a column named id and increase it's value as record are inserted. Because you can't delete on base of id that is created automatically by database

Categories