How to view all data from database? - java

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())

Related

Sum two numbers in SQL database

I have a program to sum two numbers and save result in SQL then show results in a TextView but I don't know how to make that; help me please.
But this number comes from the user (EditText) or from button ...
must I make a new table for the sum number for example or what .
I watch videos on you tube but I can do it that program.
this my code...
in DataBase activity :
public class DB_sql extends SQLiteOpenHelper {
public static final String name = "data.db";
public static final String TABLE_NAME="mydata";
public static final String KEY_First="first";
public static final String KEY_second="second";
public DB_sql(#Nullable Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table TABLE_NAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, KEY_First INTEGER, KEY_second INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS TABLE_NAME");
onCreate(db);
}
public boolean insertdata (int first,int second){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues numbers = new ContentValues();
numbers.put("first",first);
numbers.put("second",second);
long result = db.insert(TABLE_NAME,null,numbers);
if (result == -1)
return false;
else
return true;
}
in result activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
result = (TextView)findViewById(R.id.result);
int first = getIntent().getIntExtra("number1",0);
int second = getIntent().getIntExtra("number2",0);
Boolean dataSQL = db_sql.insertdata(first,second);
if (dataSQL == true){
Toast.makeText(this,"data inserted",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"data not inserted",Toast.LENGTH_SHORT).show();
}
in MainActivity:
public class MainActivity extends AppCompatActivity {
// DB_sql db_sql = new DB_sql(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void second(View view) {
Intent sec = new Intent(this,result.class);
sec.putExtra("number2",40);
startActivity(sec);
}
public void first(View view) {
Intent fir=new Intent(this,result.class);
fir.putExtra("number1",85);
startActivity(fir);
}
}

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();

Database can not be created

These are the logcat errors which repeat 3 or 4 times when I run the app. I attached the database helper:
Error inserting time_type=3 proto_blob=[B#42439540 sync_state_mod_time_millis=1466838685054 context_id=e7029963-e329-4b1b-bb6e-24bb57e0ba04 end_time=1466837904524 module_id=com.google.android.contextmanager.module.ScreenModule start_time=1466837558811 sync_state=0 context_family=7 context_name=7 version=1
android.database.sqlite.SQLiteConstraintException: column context_id is not unique (code 19)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
at bsv.a(SourceFile:445)
at bsv.b(SourceFile:420)
at bsv.a(SourceFile:370)
at bsv.a(SourceFile:147)
at bsc.a(SourceFile:157)
at bjb.a(SourceFile:64)
at bix.run(SourceFile:52)
at biv.a(SourceFile:258)
at biv.handleMessage(SourceFile:251)
at jcq.run(SourceFile:141)
at jcy.run(SourceFile:438)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at jhi.run(SourceFile:17)
at java.lang.Thread.run(Thread.java:841)
This is the Databasehelper class:
public class databasehelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="USMS.db";
public static final String TABLE_NAME="B_LIST";
public static final String COL1="ID";
public static final String COL2="NAME";
public static final String COL3="NUMBER";
public databasehelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create Table "+TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, name text, number 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 name, String number) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values =new ContentValues();
values.put(COL2,name);
values.put(COL3,number);
Long result = db.insert(TABLE_NAME, null ,values);
if(result==-1)
return false;
else
return true;
}
}
and this is my Main Activity class:
public class MainActivity extends AppCompatActivity {
databasehelper myDb;
EditText editname,editnumber;
Button bt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb=new databasehelper(this);
editname = (EditText)findViewById(R.id.editText);
editnumber = (EditText)findViewById(R.id.editText2);
bt1 = (Button) findViewById(R.id.button);
}
public void adddate(){
bt1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
boolean inserted = myDb.InsertData(editname.getText().toString(),editnumber.getText().toString());
if (inserted=true)
Toast.makeText(MainActivity.this,"data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"not inserted",Toast.LENGTH_LONG).show();
}
});
}
}
I hope someone can help me, thanks in advance!

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

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;
}

Creating a database in SQLite before opening

I wish to query my username against an already existing table in the database. But when I executed my code, my app force closed due to "SQLite returned error code: 1, msg = near "=": syntax error.
Here is the DBAdapter.java file
package com.example.usernammepassword;
import android.content.ContentValues;
public class DBAdapter {
public static final String KEY_NAME = "UserName";
public static final String KEY_PASS = "Password";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "Test";
private static final String DATABASE_TABLE = "UsernamePassword";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table if not exists UsernamePassword (UserName text not null primary key, Password text not null);";
private final Context context;
DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db1) {
try {
db1.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public DBAdapter open() throws SQLException {
public void close() {
public long insertNewUser(String UserName, String Password) {
public boolean deleteUser(String UserName)
public Cursor getAllUserNamesAndPasswords()
{
return db.query(DATABASE_TABLE, new String[] { KEY_NAME,
KEY_PASS}, null, null, null, null, null);
}
public Cursor getPasswordForUserName(String UserName) throws SQLException
public boolean updatePasswordForUserName( String UserName, String Password) {
}
And the MainActivity.java file
package com.example.usernammepassword;
import android.os.Bundle;
public class MainActivity extends Activity {
private String md5(String in) {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText text = (EditText)findViewById(R.id.editText1);
EditText text1 = (EditText)findViewById(R.id.editText2);
String userid = text.getText().toString();
String pass = text1.getText().toString();
Toast.makeText(MainActivity.this,"Entered "+userid+" and password entered is "+pass,Toast.LENGTH_LONG).show();
pass = md5(pass + "#string/salt");
Toast.makeText(MainActivity.this,"Password after adding a salt and md5 hashing is now equal to " + pass,Toast.LENGTH_LONG).show();
DBAdapter db = new DBAdapter(MainActivity.this);
db.open();
Cursor c = db.getPasswordForUserName(userid);
if(c.moveToFirst())
{
if(c.getString(1) == pass)
{
Toast.makeText(MainActivity.this, "Authentication Succeded", Toast.LENGTH_SHORT).show();
//proceed
}
else
{
Toast.makeText(MainActivity.this, "#string/AuthFail", Toast.LENGTH_SHORT).show();
//AuthFailure
}
}
else
{
Toast.makeText(MainActivity.this,"#string/UserNotFound", Toast.LENGTH_SHORT).show();
//where to from here
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
}
The Logcat:
You probably updated your table name from something to UserNamePassword, but didn't change the DATABASE_VERSION, which will trigger onUpgrade().
Of course onUpgrade() has to be implemented as well to create the appropriate table.

Categories