database.sqlite.SQLiteOpenHelper.getDatabaseLocked+Null PointerExpception Error Android Studio - java

I am working on android application that need to get data from table using sqlite and show the specific items in the list view. As I try to run the application the application got error getDatabaseLocked and show error on sqlite database...
here is my sqlite file..
{
private static final int DATABASE_VERSION = 2;
Context context;
private static final String DATABASE_NAME = "DynamicERP.db";
public static final String table_orders = "TABLEORDERS";
public static final String table_poducts_records = "PRODUCTSRECORDS";
public static final String code = "ORDERCODE";
public static final String barcode = "BARCODE";
public static final String nametblp = "NAME";
public static final String size = "SIZE";
public static final String uname = "UNAME";
public static final String retail = "RETAIL";
public static final String wholesale = "WHOLESALE";
public static final String trade = "TRADE";
public static final String percentage = "PERCENTAGE";
public static final String tax = "TAX";
public static final String subcatagary = "SUBCATAGARY";
public static final String categary = "CATEGARY";
public static final String company = "COMPANY";
public static final String type = "TYPE";
public static final String packsize = "PACKSIZE";
public static final String weight = "WEIGHT";
public static final String weightunit = "WEIGHTUNIT";
public static final String currentstock = "CURRENTSTOCK";
public static final String salecode = "SALECODE";
public static final String mcode = "MCODE";
public static final String fname = "FIRSTNAME";
public static final String lname = "LASTNAME";
public static final String urduname = "URDUNAME";
public static final String address = "ADDRESS";
public static final String contact = "CONTACT";
public static final String cnic = "CNIC";
public static final String saletype = "TYPE";
public static final String route = "ROUTE";
public static final String area = "AREA";
public static final String zone = "ZONE";
public static final String balance = "BALANCE";
public static final String creditlimit = "CREDITLIMIT";
public static final String spl = "SPL";
public static final String saletax = "SALETAX";
private static final String DATABASE_ORDERS = "CREATE TABLE " + table_orders + "("
+ code + " INTEGER, " + barcode + " VARCHAR," + nametblp + " VARCHAR," + size + " VARCHAR," + uname +
" VARCHAR," + retail + " VARCHAR," + wholesale + " VARCHAR," + trade + " VARCHAR,"
+ percentage + " VARCHAR," + tax + " VARCHAR," + subcatagary + " VARCHAR," + categary + " VARCHAR," +
company + " VARCHAR," + type + " VARCHAR," + packsize + " VARCHAR," +
weight + " VARCHAR," + weightunit + " VARCHAR, " + currentstock + " VARCHAR );";
private static final String DATABASE_PRODUCTS = "CREATE TABLE " + table_poducts_records + "("
+ salecode + " INTEGER, " + mcode + " VARCHAR, " + fname + " VARCHAR, " + lname + " VARCHAR, " + urduname +
" VARCHAR, " + address + " NVARCHAR, " + contact + " VARCHAR," + cnic + " VARCHAR, " + saletype + " VARCHAR,"
+ route + " VARCHAR, " + area + " VARCHAR," + zone + " VARCHAR," +
balance + " VARCHAR, " + creditlimit + " VARCHAR," + spl + " VARCHAR, " + saletax + " VARCHAR);";
private String DROP_ORDER_REC = "DROP TABLE IF EXISTS " + table_orders;
private String DROP_PRODUCTS_REC = "DROP TABLE IF EXISTS " + table_poducts_records;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_ORDERS);
db.execSQL(DATABASE_PRODUCTS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_PRODUCTS_REC);
db.execSQL(DROP_ORDER_REC);
onCreate(db);
}
public List<GetSetOrders> getAllOrderData() {
String[] columns = {
nametblp,
code,
retail,
subcatagary,
company
};
String sortOrder = code + " ASC";
SQLiteDatabase db = this.getReadableDatabase();
db.isOpen();
List<GetSetOrders> clientlist = new ArrayList<GetSetOrders>();
Cursor cursor = db.query(table_poducts_records, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
if (cursor.moveToFirst()) {
do {
GetSetOrders orders = new GetSetOrders();
orders.setNAME(cursor.getString(cursor.getColumnIndex(nametblp)));
orders.setORDERCODE(cursor.getString(cursor.getColumnIndex(code)));
orders.setRETAIL(cursor.getString(cursor.getColumnIndex(retail)));
orders.setCATEGARY(cursor.getString(cursor.getColumnIndex(subcatagary)));
orders.setCOMPANY(cursor.getString(cursor.getColumnIndex(company)));
clientlist.add(orders);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return clientlist;
}
Here is my crash log which shows the error of the database close
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
at com.example.tablewithlist.DatabaseHelper.getAllOrderData(DatabaseHelper.java:182)
at com.example.tablewithlist.Clients$2.doInBackground(Clients.java:67)
at com.example.tablewithlist.Clients$2.doInBackground(Clients.java:63)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
Here is my Adapter Class
{
private List<GetSetOrders> listOrders;
Context mContext;
RecyclerView mRecyclerView;
View itemView;
public ClientRecyclerAdapter(List<GetSetOrders> listOrders, RecyclerView recyclerView) {
this.listOrders = listOrders;
mRecyclerView = recyclerView;
}
#Override
public ClientViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.items_products_table, parent, false);
return new ClientViewHolder(itemView);
}
public class ClientViewHolder extends RecyclerView.ViewHolder {
//public AppCompatTextView ID;
public TextView lblPName;
public TextView lblTrade;
public TextView lblRetail;
public TextView lblSubCategary;
public TextView lblCompany;
RelativeLayout layout;
public ClientViewHolder(View view) {
super(view);
lblPName = view.findViewById(R.id.lblPName);
lblTrade = view.findViewById(R.id.lblTrade);
lblRetail = view.findViewById(R.id.lblRetail);
lblSubCategary = view.findViewById(R.id.lblSubCategary);
lblCompany = view.findViewById(R.id.lblCompany);
layout = view.findViewById(R.id.listprod);
}
}
#Override
public void onBindViewHolder(ClientViewHolder holder, final int position) {
holder.lblPName.setText(listOrders.get(position).getNAME());
holder.lblTrade.setText(listOrders.get(position).getORDERCODE());
holder.lblRetail.setText(listOrders.get(position).getRETAIL());
holder.lblSubCategary.setText(listOrders.get(position).getSUBCATAGARY());
holder.lblCompany.setText(listOrders.get(position).getCOMPANY());
holder.layout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(mContext, "ABC", Toast.LENGTH_SHORT).show();
return false;
}
});
}
#Override
public int getItemCount() {
Log.v(ClientRecyclerAdapter.class.getSimpleName(), "" + listOrders.size());
return listOrders.size();
}
}
This is the main class where I am calling the function of the database...
{
Activity activity;
RecyclerView recyclerViewClients;
Button btnAll;
ClientRecyclerAdapter clientRecyclerAdapter;
List<GetSetOrders> listclients;
DatabaseHelper databaseHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.clients, container, false);
btnAll=view.findViewById(R.id.searchall);
recyclerViewClients=view.findViewById(R.id.Viewclients);
listclients = new ArrayList<>();
clientRecyclerAdapter = new ClientRecyclerAdapter(listclients,recyclerViewClients);
recyclerViewClients.setItemAnimator(new DefaultItemAnimator());
recyclerViewClients.setItemAnimator(new DefaultItemAnimator());
recyclerViewClients.setHasFixedSize(true);
recyclerViewClients.setAdapter(clientRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
btnAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getClientFromSqlite();
Toast.makeText(getActivity(), "Usman", Toast.LENGTH_SHORT).show();
}
});
return view;
}
private void getClientFromSqlite() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listclients.clear();
listclients.addAll(databaseHelper.getAllOrderData());
// clientRecyclerAdapter.notifyDataSetChanged();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
clientRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
Here is my Fragment activity which contain Viewpager class client..
{
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_fragment);
databaseHelper=new DatabaseHelper(this);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Dynamic ERPMini");
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Clients"));
tabLayout.addTab(tabLayout.newTab().setText("Products"));
tabLayout.addTab(tabLayout.newTab().setText("Invoices"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new PagersAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
The New Error Crash Log by updating the code..
android.database.sqlite.SQLiteException: no such column: NAME (code 1): , while compiling: SELECT NAME, ORDERCODE, RETAIL, SUBCATAGARY, COMPANY FROM PRODUCTSRECORDS ORDER BY ORDERCODE ASC
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
at com.example.tablewithlist.DatabaseHelper.getAllOrderData(DatabaseHelper.java:175)
at com.example.tablewithlist.Clients$2.doInBackground(Clients.java:65)
at com.example.tablewithlist.Clients$2.doInBackground(Clients.java:61)
at android.os.AsyncTask$2.call(AsyncTask.java:287)

Could you check the context received by DataBaseHelper constructor. May be it has NULL value.
Try this,
databaseHelper = new DatabaseHelper(getActivity());
For Second issue, You need to revisit to your table structure or query construction. Error log said there is no column named as "NAME" in table which is your querying table. Please check once again the basics.

Related

java.lang.NoSuchMethodException: perfIOPrefetchStart [duplicate]

public class Main2Activity extends AppCompatActivity {
private EditText editText1, editText2, editText3, editText4;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
editText4 = (EditText) findViewById(R.id.editText4);
button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String un, pw, cpw, ph;
un = editText1.getText().toString();
pw = editText2.getText().toString();
cpw = editText3.getText().toString();
ph = editText4.getText().toString();
DbHelper dbHelpero = new DbHelper(Main2Activity.this);
SQLiteDatabase db = dbHelpero.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Entry.C_UNAME, un);
values.put(Entry.C_PASS, pw);
values.put(Entry.C_CPASS, cpw);
values.put(Entry.C_PNO, ph);
long newRowId = db.insert(Entry.TABLE_NAME, null, values);
if (newRowId == -1) {
Toast.makeText(getApplicationContext(), "Error while adding", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Yo Registration is complete", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is the Contract.java
public class Contract {
private Contract() {
}
public static final class Entry implements BaseColumns {
public final static String TABLE_NAME = "details";
public final static String _ID = BaseColumns._ID;
public final static String C_UNAME = "uname";
public final static String C_PASS = "pw";
public final static String C_CPASS = "cpw";
public final static String C_PNO = "pno";
}
}
And the DbHelper.java
public class DbHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = DbHelper.class.getSimpleName();
public final static String DATABASE_NAME = "contacts.db";
private static final int DATABASE_VERSION = 1;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " TEXT PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
There are no syntax errors but still, the app is crashing.
Replace your CREATE_TABLE query with:
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
You can't have a TEXT type have an AUTOINCREMENT property as you currently have it on your _ID field. You need to change it to be an INTEGER so it can be used as PRIMARY KEY and then have it AUTOINCREMENT

SQLITE DATABASE error in displaying data to listview

im getting problem in displaying my data from sqlite db
my apps stops working when run and display no errors.
please help me
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "ExpDatee.db";
public static final String TABLE_NAME = "EXPDATE_TABLE";
public static final String COL_1 = "PRO_ID";
public static final String COL_2 = "PRO_NAME";
public static final String COL_3 = "PRO_EXPDATE";
public static final String COL_4 = "PRO_DAYTILLEXP";
/**
private static final String SQL_CREATE_TABLE_EXPDATE = "CREATE TABLE " + TABLE_NAME + "("
+ PRO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PRO_NAME + " TEXT NOT NULL, "
+ PRO_EXPDATE+ " TEXT NOT NULL, "
+ PRO_DAYTILLEXP + " TEXT NOT NULL, "
+ ");";
**/
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 + "(PRO_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"PRO_NAME TEXT, " +
"PRO_EXPDATE TEXT," +
" PRO_DAYTILLEXP TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
//method to insert data
public boolean insertData(String PRO_NAME, String PRO_EXPDATE, String PRO_DAYTILLEXP)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,PRO_NAME);
contentValues.put(COL_3,PRO_EXPDATE);
contentValues.put(COL_4,PRO_DAYTILLEXP);
Log.d(TAG, "ADD DATA : ADDING " + PRO_NAME + " TO " + TABLE_NAME);
Log.d(TAG, "ADD DATA : ADDING " + PRO_EXPDATE + " TO " + TABLE_NAME);
Log.d(TAG, "ADD DATA : ADDING " + PRO_DAYTILLEXP + " TO " + TABLE_NAME);
long result = db.insert(TABLE_NAME,null ,contentValues );
if (result == -1)
return false;
else
return true;
}
//get all data
public Cursor getData()
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM" + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etProductName, etDaysBeforeExp, etExpDate;
Button btnAddItem, btnViewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etProductName = (EditText)findViewById(R.id.etProductName);
etDaysBeforeExp = (EditText)findViewById(R.id.etDaysBeforeExp);
etExpDate = (EditText)findViewById(R.id.etExpDate);
btnAddItem = (Button)findViewById(R.id.btnAddItem);
btnViewItem = (Button)findViewById(R.id.btnViewItem);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String PRO_NAME = etProductName.getText().toString();
String PRO_EXPDATE = etExpDate.getText().toString();
String PRO_DAYTILLEXP = etDaysBeforeExp.getText().toString();
if(etProductName.length() !=0)
{
AddData(PRO_NAME,PRO_EXPDATE,PRO_DAYTILLEXP);
etProductName.setText("");
etExpDate.setText("");
etDaysBeforeExp.setText("");
}
else
{
toastMessage("PLEASE INSERT VALUE");
}
}
});
btnViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String PRO_NAME, String PRO_EXPDATE, String PRO_DAYTILLEXP)
{
boolean InsertData = myDB.insertData(PRO_NAME,PRO_EXPDATE,PRO_DAYTILLEXP);
if(InsertData)
{
toastMessage("DATA INSERTED");
}
else
{
toastMessage("DATA NOT INSERTED");
}
}
private void toastMessage(String message) {
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
ListDataActivity.java
public class ListDataActivity extends AppCompatActivity {
DatabaseHelper myDB;
private ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
populateListView();
}
private void populateListView() {
Cursor data = myDB.getData();
ArrayList<String> listData = new ArrayList<>();
while (data.moveToNext())
{
listData.add(data.getString(1));
listData.add(data.getString(2));
listData.add(data.getString(3));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
}
private void toastMessage(String message) {
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
Initialized Listdataactivity
myDB = new DatabaseHelper(this);
Use Arrayadapter
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);

Unable to insert data into database within fragment

I'm using fragment to create tabs, and I'm trying to insert information from the fragment to my database.
So I've 3 RadioGroup and I'm adding to the database the 'Checked' radio button that the user has marked, and I'm not able to add into the database the data because the following error:
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
There are DatabaseHandler functions (which works) that I use such as
db.checkSetting() - Check if the database table is empty, if empty return false, if not return true.
db.updateSetting() - Update the data inside the table.
db.addSetting() - Create new table with new data.
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
//table name
private static final String TABLE_DETAILS = "details";
private static final String TABLE_FOOD = "food";
private static final String TABLE_OLDDETAILS = "oldDetails";
private static final String TABLE_SETTING = "setting";
//Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_HEIGHT = "height";
private static final String KEY_WEIGHT = "weight";
private static final String KEY_CALORIES = "calories";
private static final String KEY_DATE = "date";
private static final String KEY_LEVEL = "level";
private static final String KEY_DURATION = "duration";
private static final String KEY_DAYS = "days";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DETAILS_TABLE = "CREATE TABLE " + TABLE_DETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_FOOD_TABLE = "CREATE TABLE " + TABLE_FOOD + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_CALORIES + " INTEGER " + ")";
String CREATE_OLDDETAILS_TABLE = "CREATE TABLE " + TABLE_OLDDETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_SETTING_TABLE = "CREATE TABLE " + TABLE_SETTING + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_LEVEL + " INTEGER," + KEY_DURATION + " INTEGER," + KEY_DAYS + " INTEGER " + ")";
db.execSQL(CREATE_OLDDETAILS_TABLE);
db.execSQL(CREATE_DETAILS_TABLE);
db.execSQL(CREATE_FOOD_TABLE);
db.execSQL(CREATE_SETTING_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_OLDDETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOOD);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTING);
// Create tables again
onCreate(db);
}
public boolean addSetting(int level, int duration, int days) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, 1);
values.put(KEY_LEVEL, level);
values.put(KEY_DURATION, duration);
values.put(KEY_DAYS, days);
// Inserting Row
long result = db.insert(TABLE_SETTING, null, values);
if(result == -1){
return false;
}
else{
return true;
}
}
public boolean checkSetting(){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
Cursor cursor = db.rawQuery(selectQuery, null);
Boolean rowExists;
if (cursor.moveToFirst())
{
// DO SOMETHING WITH CURSOR
rowExists = true;
} else
{
// I AM EMPTY
rowExists = false;
}
return rowExists;
}
public setting getSetting() {
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
setting set = new setting(cursor.getInt(1), cursor.getInt(2), cursor.getInt(3));
return set;
}
public int updateSetting(setting set) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LEVEL, set.getLevel());
values.put(KEY_DURATION, set.getDuration());
values.put(KEY_DAYS, set.getDays());
Log.d("UPDATE: ", "updated all");
// updating row
return db.update(TABLE_SETTING, values, KEY_ID + " = ?", new String[] { String.valueOf(1) });
}
Fragment:
public class PageFragment extends Fragment {
DatabaseHandler db = new DatabaseHandler(getActivity()); //DATABASE
private int group1;
private int group2;
private int group3;
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_training, container, false);
ViewStub stub = (ViewStub) view.findViewById(R.id.stub);
if(mPage == 1) { // mPage represents the ID of the tab/page/fragment that in use.
stub.setLayoutResource(R.layout.fragment_trainingone); // Sets resource for each fragment
View inflated = stub.inflate();
return inflated;
}
else{
stub.setLayoutResource(R.layout.fragment_trainingtwo);
View inflated = stub.inflate();
RadioGroup rg1 = (RadioGroup) inflated.findViewById(R.id.group1);
RadioGroup rg2 = (RadioGroup) inflated.findViewById(R.id.group2);
RadioGroup rg3 = (RadioGroup) inflated.findViewById(R.id.group3);
Button update = (Button) inflated.findViewById(R.id.update);
rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
group1 = 1;
break;
case R.id.radio2:
group1 = 2;
break;
case R.id.radio3:
group1 = 3;
break;
}
}
});
rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio11:
group2 = 1;
break;
case R.id.radio22:
group2 = 2;
break;
case R.id.radio33:
group2 = 3;
break;
}
}
});
rg3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio111:
group3 = 1;
break;
case R.id.radio222:
group3 = 2;
break;
case R.id.radio333:
group3 = 3;
break;
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
setting set = new setting(group1, group2, group3);
if (db.checkSetting()) {
db.updateSetting(set);
} else {
db.addSetting(group1, group2, group3);
}
}
});
return inflated;
}
}
}
How can I insert data into database within fragment and avoiding NullPointerException?
You're calling
DatabaseHandler db = new DatabaseHandler(getActivity());
before the Activity is even attached to the Fragment. Initialise it in the onCreate(), or onAttach() method, so getActivity() doesn't return null.
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
According to Exception You Have to open database before querying from it follow the below linked post
public void openDataBase() throws SQLException
{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
SQLite database status on app uninstall

Data wont insert and display on my app | Android Studio

My app isn't displaying the data i'm inserting into the interface, i'm creating a fighter database where my coach can add fighters from the gym into it. I'm using a card view and recycling adaptor to display all the data but when I click submit it wont display.
Error log:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ArrayList<Item>list = new ArrayList<Item>();
private ItemAdapter adapter;
private RecyclerView recyclerView;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fetchRecords();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getLayoutInflater();
View mView1 = inflater.inflate(R.layout.activity_add,null);
final EditText input_name = (EditText) mView1.findViewById(R.id.Name);
final EditText input_age = (EditText) mView1.findViewById(R.id.Age);
final EditText input_weight = (EditText) mView1.findViewById(R.id.Weight);
final EditText input_height = (EditText) mView1.findViewById(R.id.Height);
final EditText input_reach = (EditText) mView1.findViewById(R.id.Reach);
final Button btnSave = (Button) mView1.findViewById(R.id.btnSave);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(mView1).setTitle("Add new Record")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialog.dismiss();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = input_name.getText().toString();
String age = input_age.getText().toString();
String weight = input_weight.getText().toString();
String height = input_height.getText().toString();
String reach = input_reach.getText().toString();
if (name.equals("") && age.equals("") && weight.equals("") && height.equals("")&& reach.equals("")){
Snackbar.make(view,"Field incomplete",Snackbar.LENGTH_SHORT).show();
}else {
Save(name,age,name,height,reach);
dialog.dismiss();
Snackbar.make(view,"Saving",Snackbar.LENGTH_SHORT).show();
}
}
});
dialog = builder.create();
dialog.show();
}
});
}
public void fetchRecords() {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
adapter = new ItemAdapter(this,list);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
list.clear();
Functions functions = new Functions(MainActivity.this);
ArrayList<Item>data = functions.getAllRecords();
if (data.size()>0){
for (int i = 0; i<data.size(); i++){
int id = data.get(i).getId();
String namel = data.get(i).getName();
String agel = data.get(i).getAge();
String weightl = data.get(i).getWeight();
String heightl = data.get(i).getHeight();
String reachl = data.get(i).getReach();
Item item = new Item();
item.setId(id);
item.setName(namel);
item.setAge(agel);
item.setWeight(weightl);
item.setHeight(heightl);
item.setReach(reachl);
list.add(item);
}adapter.notifyDataSetChanged();
}else {
Toast.makeText(MainActivity.this, "No Records found.", Toast.LENGTH_SHORT).show();
}
}
private void Save(String name, String age, String weight, String height, String reach) {
Functions functions = new Functions(MainActivity.this);
Item item = new Item();
item.setName(name);
item.setAge(age);
item.setWeight(weight);
item.setHeight(height);
item.setReach(reach);
functions.Insert(item);
Toast.makeText(MainActivity.this, "Saved...", Toast.LENGTH_SHORT).show();
fetchRecords();
}
#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_main, menu);
return true;
}
}
public class Functions extends SQLiteOpenHelper {
private static final String DB_NAME = "crud.db";
private static final int DB_VERSION = 1;
private Fighter fighter = new Fighter();
public Functions(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(fighter.CREATE_TABLE_PERSON);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + fighter.TABLE_FIGHTER);
}
public void Insert(Item item){
SQLiteDatabase database = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(fighter.ID,item.getId());
contentValues.put(fighter.NAME,item.getName());
contentValues.put(fighter.AGE,item.getAge());
contentValues.put(fighter.WEIGHT,item.getWeight());
contentValues.put(fighter.HEIGHT,item.getHeight());
contentValues.put(fighter.REACH,item.getReach());
database.insert(fighter.TABLE_FIGHTER,null,contentValues);
}
public ArrayList<Item>getAllRecords(){
ArrayList<Item>list = new ArrayList<Item>();
SQLiteDatabase database = getReadableDatabase();
String sql = "SELECT * FROM " + fighter.TABLE_FIGHTER;
Cursor cursor = database.rawQuery(sql,null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setAge(cursor.getString(2));
item.setWeight(cursor.getString(3));
item.setHeight(cursor.getString(4));
item.setReach(cursor.getString(5));
list.add(item);
}while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
public Item getSingleItem(int id){
SQLiteDatabase database = getReadableDatabase();
String sql = "SELECT * FROM " + fighter.TABLE_FIGHTER + " WHERE " + fighter.ID + "=?";
Cursor cursor = database.rawQuery(sql,new String[]{String.valueOf(id)});
if (cursor != null)
cursor.moveToNext();
Item item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setAge(cursor.getString(2));
item.setWeight(cursor.getString(3));
item.setHeight(cursor.getString(4));
item.setReach(cursor.getString(4));
cursor.close();
database.close();
return item;
}
public void DeleteItem(int id){
SQLiteDatabase database = getWritableDatabase();
database.delete(fighter.TABLE_FIGHTER,fighter.ID + "=?",new String[]{String.valueOf(id)});
database.close();
}
public void Update(Item item){
SQLiteDatabase database = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(fighter.NAME,item.getName());
contentValues.put(fighter.AGE,item.getAge());
contentValues.put(fighter.WEIGHT,item.getWeight());
contentValues.put(fighter.HEIGHT,item.getHeight());
contentValues.put(fighter.REACH,item.getReach());
database.update(fighter.TABLE_FIGHTER,contentValues,fighter.ID + "=?",new String[]{String.valueOf(item.getId())});
}
}
public class Fighter {
public static final String TABLE_FIGHTER = "fighter";
public static final String ID = "ID";
public static final String NAME = "Name";
public static final String AGE = "Age";
public static final String WEIGHT = "Weight";
public static final String HEIGHT = "Height";
public static final String REACH = "Reach";
public static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_FIGHTER + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ AGE + " TEXT,"
+ WEIGHT + " TEXT,"
+ HEIGHT + " TEXT"
+ REACH + " TEXT"+ ")";
}
According to your code, you have missed a comma after + HEIGHT + " TEXT" . therefore table is not created properly due to SQL syntax errors. please try with following. i have added the comma for you.
public static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_FIGHTER + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ AGE + " TEXT,"
+ WEIGHT + " TEXT,"
+ HEIGHT + " TEXT,"
+ REACH + " TEXT"+ ")";

SQLiteDatabase not displaying information ImageButton Crashes App

I'm creating a Calorie App for my class project. I attempted to implement a database to store the information of the calories added by the user which would be displayed in a listview. The user will input the calories in the add_entry fragment and be displayed on the fragment_home page in the listview.
Problem: I'm not sure if I'm adding the information correctly to the database using the Entry Add Fragment in order to display the info in the listview. this is my first time working with Android Studio/App.
Problem 2:
For Some Reason when I click on imagebutton on my homefragment app crashes and
it doesnt go to the add_entry fragment
logcat:
04-06 00:33:41.213 30567-30567/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 30567
java.lang.IllegalStateException: Could not find method Click(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'AddItems'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
listview = (ListView) getActivity().findViewById(R.id.listView);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber - FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID,
KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
return db.insert(DATABASE_TABLE, null, initialValues);
}
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();
}
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;
}
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;
}
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
}
}
}
AddEntry.java
public class AddEntry extends Fragment implements
View.OnClickListener {
EditText DescriptionET,CalorieET;
ImageButton savebtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_entry, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
break;
case R.id.CancelBtn:
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private static final String DATABASE_NAME = "CalorieDb.db";
And then call below method in oncreat()
public void checkDB() {
try {
//android default database location is : /data/data/youapppackagename/databases/
String packageName = this.getPackageName();
String destPath = "/data/data/" + packageName + "/databases";
String fullPath = "/data/data/" + packageName + "/databases/"
+ DATABASE_NAME;
//this database folder location
File f = new File(destPath);
//this database file location
File obj = new File(fullPath);
//check if databases folder exists or not. if not create it
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
}
//check database file exists or not, if not copy database from assets
if (!obj.exists()) {
this.CopyDB(fullPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Unintall app and clean and rebuild project then I think solve your problem.
Try Replaceing this, Removing the last Comma(,) from the statement
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
Remove , from last field
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private static final String DATABASE_CREATE_SQL =
" create table " + DATABASE_TABLE
+ " ( " + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ " ); ";
Add space " ) "

Categories

Resources