I can't get the data - java

I can't get the data from a database.
Can you help me, please?
Error Log :
1-10091/com.example.dogruprint.dogruprint2 E/AndroidRuntime﹕ FATAL EXCEPTION: main android.database.sqlite.SQLiteException: no such table: users (code 1): , while compiling: SELECT _id, u_name, u_pass FROM
users
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.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.(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.dogruprint.dogruprint2.Database.getThat(Database.java:123)
at com.example.dogruprint.dogruprint2.siparisekle$2.onClick(siparisekle.java:113)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
DATABASE.java
package com.example.dogruprint.dogruprint2;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.sql.SQLException;
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "u_name";
public static final String KEY_PASS = "u_pass";
private static final String DB_NAME = "app";
private static final String DB_TABLE = "users";
private static final int version = 1;
private SQLiteDatabase ourDatabase;
private DBHelper ourHelper;
private Context ourContext;
private SQLiteDatabase writableDatabase;
public Database(Context context) {
ourContext = context;
}
public SQLiteDatabase getWritableDatabase() {
return writableDatabase;
}
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context)
{
super(context, DB_NAME, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
/*
final String CREATE_TABLE = " CREATE TABLE " + DB_TABLE + " ( " + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ KEY_NAME + " VARCHAR(255) , "
+ KEY_PASS + " VARCHAR(255) ,"
;
*/
String CREATE_USERS_TABLE = "CREATE TABLE " + DB_TABLE + "(" + KEY_ROWID +
" INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PASS + " TEXT"
+ ");";
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + DB_TABLE);
}
}
public Database open() throws SQLException {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public Database close() {
ourHelper.close();
return this;
}
public void addThat(String name, String pass) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_PASS, pass);
ourDatabase.insert(DB_TABLE, null, cv);
}
public String getThat()
{
String[] colomns = new String[]{KEY_ROWID,KEY_NAME,KEY_PASS};
Cursor c = ourDatabase.query(DB_TABLE,colomns,null,null,null,null,null);
int İROW = c.getColumnIndex(KEY_ROWID);
int İNAME= c.getColumnIndex(KEY_NAME);
int İPASS = c.getColumnIndex(KEY_PASS);
String result = "";
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
result = result + "name" + c.getString(İNAME) + "pass" + c.getString(İPASS)+"\n";
}
return result;
}
}
siparisekle.java
package com.example.dogruprint.dogruprint2;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.sql.SQLException;
import static android.R.*;
public class siparisekle extends Activity {
private AutoCompleteTextView act1, act2, act3;
private EditText edittxt1;
EditText etName,etPass;
TextView tvResult;
Button bSave;
Button bShow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_siparisekle);
final Database db = new Database(this);
install_elements();
bSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean ok = true;
String name = etName.getText().toString();
String pass = etPass.getText().toString();
try {
db.open();
db.addThat(name, pass);
tvResult.setText(name + "Eklendi");
db.close();
} catch (Exception e) {
ok = false;
e.printStackTrace();
tvResult.setText("Sorun var");
} finally {
if (ok) {
Dialog d = new Dialog(siparisekle.this);
TextView tv = new TextView(siparisekle.this);
tv.setText("BASARILI");
d.setTitle("Sonuç");
d.setContentView(tv);
d.show();
}
}
}
});
bShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
try {
db.open();
String data = db.getThat();
tvResult.setText(data);
db.close();
} catch (SQLException e)
{
Toast.makeText(getApplicationContext(),"Çağırmada Bir Sorun Oluştu",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
protected void install_elements()
{
etName = (EditText) findViewById(R.id.etName);
etPass= (EditText) findViewById(R.id.etPass);
tvResult= (TextView) findViewById(R.id.tvResult);
bSave= (Button) findViewById(R.id.bSave);
bShow= (Button) findViewById(R.id.bShow);
}
}

The exception message says this:
no such table: users (code 1) while compiling "SELECT _id, u_name, u_pass FROM users"
It is looking for a table called "users" in the database, but it can't find one!
Either you haven't set up your database correctly (e.g. you haven't created the tables) or the schema (e.g. table names) for your database doesn't match what the application requires.
In fact, look at your onCreate method. All it is doing is creating and throwing away a string containing some SQL. You need to execute it ....

You really need to execute your table creation:
String CREATE_USERS_TABLE = "CREATE TABLE " + DB_TABLE + "(" + KEY_ROWID +
" INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PASS + " TEXT" + ")";
db.execSQL(CREATE_USERS_TABLE);
You also need to call your onCreate() method inside your onUpgrade() method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXIST " + DB_TABLE);
onCreate(db);
}

Related

Data doesn't get saved in database, which it did before, but after I updated the database version it doesn't

Thanks for helping me fix my problem!
Issue
The issue is that the data never gets saved into the database, which it did before, but then i updated the database version and now it does not.
Is there an error thrown? Yes there is and its right down below.
E/SQLiteLog: (1) near "0": syntax error
E/SQLiteDatabase: Error inserting 0=20 id=csdfergeg userid=csdfergeg email=erregegergr
android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO Info(0,id,userid,email) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1417)
at com.vikkivuk.mxelevator.Database.addUserInfo(Database.java:50)
at com.vikkivuk.mxelevator.finishScene$1.onClick(finishScene.java:61)
at android.view.View.performClick(View.java:6294)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
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)
My code:
Database Class:
package com.vikkivuk.mxelevator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " TEXT," + KEY_EMAIL + " TEXT," + Integer.parseInt(KEY_CODE) + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, info.UserId);
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo(){
List<UserInfo> results = new ArrayList<UserInfo>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[] {String.valueOf(info.ID)});
db.close();
}
}
UserInfo:
package com.vikkivuk.mxelevator;
public class UserInfo {
public String ID;
public String UserId;
public String Email;
public String CODE;
public UserInfo(String uid, String mail, String el_code){
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(String userId, String uid, String mail, String el_code){
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
UserInfoAdapter:
package com.vikkivuk.mxelevator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
public class UserInfoAdapter extends ArrayAdapter<UserInfo> {
public UserInfoAdapter(Context context, List<UserInfo> info) {
super(context, 0, info);
}
public View getView(int position, View convertView, ViewGroup parent){
UserInfo info = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.user_info_item_row, parent, false);
}
TextView uid = convertView.findViewById(R.id.textview_userid);
TextView email = convertView.findViewById(R.id.textview_email);
TextView textcode = convertView.findViewById(R.id.codetext);
uid.setText(info.UserId);
email.setText(info.Email);
textcode.setText(info.CODE);
return convertView;
}
}
Finish scene:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.Random;
public class finishScene extends AppCompatActivity {
EditText userId, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish_scene);
userId = findViewById(R.id.userid);
email = findViewById(R.id.email);
CheckBox agreeCheck = findViewById(R.id.agreeCheck1);
Boolean checked = agreeCheck.isChecked();
Button submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userId.length() < 5) {
Toast.makeText(getApplicationContext(), "Your UID is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (email.length() < 6) {
Toast.makeText(getApplicationContext(), "Your EMAIL is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (!agreeCheck.isChecked()) {
Toast.makeText(getApplicationContext(), "Please check the agree box!", Toast.LENGTH_SHORT).show();
return;
} else {
Random rand = new Random();
int int_random1 = rand.nextInt(10000);
int int_random2 = rand.nextInt(10);
int int_random3 = rand.nextInt(10);
int int_random4 = rand.nextInt(15);
int int_random5 = rand.nextInt(25);
int random_code = int_random1 + int_random2 + int_random3 + int_random4 + int_random5;
Database db = new Database(finishScene.this);
UserInfo info = new UserInfo(userId.getText().toString(), email.getText().toString(), String.valueOf(random_code));
db.addUserInfo(info);
db.close();
userId.setText("");
email.setText("");
Toast.makeText(getApplicationContext(), "Data saved! Pending approval...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(userId.getContext(), Success.class);
startActivity(intent);
}
}
});
}
}
ShowData:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShowData extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
List<UserInfo> info = new Database(this).getUserInfo();
UserInfoAdapter adapter = new UserInfoAdapter(this, info);
ListView listView = findViewById(R.id.userInfoList);
listView.setAdapter(adapter);
Button goback = findViewById(R.id.goback1);
goback.setOnClickListener(v -> {
Intent intent = new Intent(goback.getContext(), MainActivity.class);
startActivity(intent);
});
}
}
That's all of my classes. Also, I would like to specify that I don't actually know what database versions are since I started with the android studio 3 days ago.
please try this I implemented some change on the UserInfo class
the Id must be an integer and you add a String
database.java
public class MyBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public MyBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " INTEGER," + KEY_EMAIL + " TEXT," + KEY_CODE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// contentValues.put(KEY_ID, info.UserId); i removed this
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo() {
List<UserInfo> results = new ArrayList<>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[]{String.valueOf(info.ID)});
db.close();
}
}
and UserInfo :
public class UserInfo {
public int ID;
public int UserId;
public String Email;
public int CODE;
public UserInfo(int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(int userId, int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
i hope that's help you

Error when trying to access database copied from Assets - AndroidStudio

all day long I've been searching the root cause of the following error. I there anyone who can help me with this issue?
Using:
Android Studio 4.1.1 / Java
My goal:
I have a sqlite database created with DB Browser (recipe.db3) in my assets folder: Assets > recipe.db3. This database shall be copied to app database folder in the SplashActivity.java if the database does not exist yet (basically once in app lifetime).
Once created, I want to access this database and show its content (only title) in the RecycleViewer in RecipesFragment.java.
My issue:
I receive a NullPointerException when I try to show my RecyclerView - basically when I run this.getReadableDatabase() in my DataBaseHelper.java. It seems like I cannot even access my database. Even if I do not copy my baking.db3 file to /data/data/com.android.baking/databases/ but create the database programmatically I receive the same error.
Does anyone have a clue where the error lies?
Thanks!
Kornelius
Logcat output
I/database: TABLE_RECIPES created
TABLE_US created
...............
D/EGL_emulation: eglMakeCurrent: 0xb31050c0: ver 2 0 (tinfo 0xb3103660)
I/art: Do partial code cache collection, code=55KB, data=59KB
After code cache collection, code=54KB, data=58KB
Increasing code cache capacity to 256KB
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.baking, PID: 9878
androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.android.baking.ui.recipes.RecipesFragment: calling Fragment constructor caused an exception
at androidx.fragment.app.Fragment.instantiate(Fragment.java:566)
at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390)
at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58)
at androidx.navigation.NavController.navigate(NavController.java:1059)
at androidx.navigation.NavController.navigate(NavController.java:944)
at androidx.navigation.NavController.navigate(NavController.java:877)
at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.java:97)
at androidx.navigation.ui.NavigationUI$5.onNavigationItemSelected(NavigationUI.java:531)
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:127)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at androidx.fragment.app.Fragment.instantiate(Fragment.java:548)
at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57) 
at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390) 
at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132) 
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162) 
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58) 
at androidx.navigation.NavController.navigate(NavController.java:1059) 
at androidx.navigation.NavController.navigate(NavController.java:944) 
at androidx.navigation.NavController.navigate(NavController.java:877) 
at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.java:97) 
at androidx.navigation.ui.NavigationUI$5.onNavigationItemSelected(NavigationUI.java:531) 
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243) 
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834) 
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158) 
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985) 
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:127) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Caused by: java.lang.NullPointerException: 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
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
at com.android.baking.DataBaseHelper.<init>(DataBaseHelper.java:64)
at com.android.baking.ui.recipes.RecipesFragment.<init>(RecipesFragment.java:37)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:430) 
at androidx.fragment.app.Fragment.instantiate(Fragment.java:548) 
at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57) 
at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390) 
at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132) 
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162) 
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58) 
at androidx.navigation.NavController.navigate(NavController.java:1059) 
at androidx.navigation.NavController.navigate(NavController.java:944) 
at androidx.navigation.NavController.navigate(NavController.java:877) 
at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.java:97) 
at androidx.navigation.ui.NavigationUI$5.onNavigationItemSelected(NavigationUI.java:531) 
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243) 
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834) 
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158) 
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985) 
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:127) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
DataBaseHelper.java:
package com.android.baking;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import android.util.Log;
import com.android.baking.ui.adapter.RecipeAdapter;
import com.android.baking.ui.models.RecipeModel;
import com.android.baking.ui.models.UserSpecificModel;
import java.util.ArrayList;
import androidx.annotation.Nullable;
public class DataBaseHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
public static String DB_NAME = "recipe.db3";
//ITEMS IN TABLE: RECIPES
public static final String TABLE_RECIPES = "RECIPES";
public static final String RECIPE_RECIPE = "RECIPE";
public static final String RECIPE_ID = "ID";
public static final String RECIPE_SOURCE = "SOURCE";
public static final String RECIPE_TITLE = "TITLE";
...............
public static final String RECIPE_ZERO_DOUGH = "ZERO_DOUGH";
public static final String RECIPE_IMAGE_1 = "IMAGE_1";
public static final String RECIPE_IMAGE_2 = "IMAGE_2";
//ITEMS IN TABLE: USER_SPECIFIC
public static final String TABLE_USER_SPECIFIC = "USER_SPECIFIC";
public static final String US_ID = "ID";
public static final String US_URL = "URL";
public static final String US_NOTES = "NOTES";
public static final String US_IS_FAVORITE = "IS_FAVORITE";
public Context context;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
this.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
//CREATE RECIPES TABLE
String createTableStatement = "CREATE TABLE " + TABLE_RECIPES + " (" + RECIPE_ID + " INTEGER PRIMARY KEY " +
"AUTOINCREMENT, " + RECIPE_SOURCE + " TEXT, " + RECIPE_TITLE + " TEXT, " + RECIPE_URL + " TEXT, " + RECIPE_DATE + " TEXT, " + RECIPE_IMGLINKS + " TEXT, " + RECIPE_DESCRIPTION + " TEXT, " + RECIPE_INGREDIENTS + " TEXT, " + RECIPE_RECIPE + " TEXT, " + RECIPE_PREPTIME_TOTAL + " TEXT, " + RECIPE_PREPTIME_BAKETIME + " TEXT, " + RECIPE_MATCOST + " TEXT, " + RECIPE_OVERNIGHT + " INTEGER, " + RECIPE_FULL_GRAIN + " INTEGER, " + RECIPE_NO_KNEAD + " INTEGER, " + RECIPE_PASTRY_TYPE + " TEXT, " + RECIPE_DOUGHS + " TEXT, " + RECIPE_TASTE + " TEXT, " + RECIPE_PORES + " TEXT, " + RECIPE_FORM + " TEXT, " + RECIPE_ZERO_DOUGH + " TEXT, " + RECIPE_IMAGE_1 + " BLOB, " + RECIPE_IMAGE_2 + " BLOB)";
db.execSQL(createTableStatement);
Log.i("database", "TABLE_RECIPES created");
//CREATE USER_SPECIFIC TABLE
createTableStatement =
"CREATE TABLE " + TABLE_USER_SPECIFIC + " (" + US_ID + " INTEGER PRIMARY KEY, " + US_URL + " TEXT, " +
US_NOTES + " TEXT, " + US_IS_FAVORITE + " INTEGER)";
db.execSQL(createTableStatement);
Log.i("database", "TABLE_US created");
}
public boolean addOneUS(UserSpecificModel userSpecificModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(US_URL, userSpecificModel.getUrl());
cv.put(US_NOTES, userSpecificModel.getNote());
cv.put(US_IS_FAVORITE, userSpecificModel.getIs_favorite());
long insert = db.insert(TABLE_USER_SPECIFIC,null, cv);
if (insert == -1) {
return false;
} else {
return true;
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
/*SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECIPES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER_SPECIFIC);
onCreate(db);*/
}
public ArrayList<RecipeModel> getAllRecipes() {
ArrayList<RecipeModel> results = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//String where = " where " + ContentDBManager.KEY_id + " = ? ";
Cursor cursor =
db.rawQuery("SELECT * FROM " + TABLE_RECIPES + " ORDER BY " + RECIPE_TITLE + " DESC", null);
if (cursor != null && cursor.getCount() > 0) {
try {
if (cursor.moveToFirst()) {
do {
RecipeModel recipeModel = new RecipeModel();
recipeModel.setId(cursor.getInt(0));
recipeModel.setSource(cursor.getString(1));
recipeModel.setUrl(cursor.getString(2));
recipeModel.setDate(cursor.getString(3));
recipeModel.setImglinks(cursor.getString(4));
recipeModel.setDescription(cursor.getString(5));
recipeModel.setIngredients(cursor.getString(6));
recipeModel.setRecipe(cursor.getString(7));
recipeModel.setPreptime_total(cursor.getString(8));
recipeModel.setPreptime_baketime(cursor.getString(9));
recipeModel.setMatcost(cursor.getString(10));
recipeModel.setOvernight(cursor.getInt(11));
recipeModel.setFull_grain(cursor.getInt(12));
recipeModel.setNo_knead(cursor.getInt(13));
recipeModel.setPastry_type(cursor.getString(14));
recipeModel.setDoughs(cursor.getString(15));
recipeModel.setTaste(cursor.getString(16));
recipeModel.setPores(cursor.getString(17));
recipeModel.setForm(cursor.getString(18));
recipeModel.setZero_dough(cursor.getString(19));
results.add(recipeModel);
} while (cursor.moveToNext());
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (!cursor.isClosed()){
cursor.close();
}
}
} else {
if (cursor != null) {
Log.i("Database",
"Cursor is Null!");
cursor.close();
}
} // to free up memory of cursor
return results;
}
}
SplashActivity.java:
package com.android.baking.ui;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import com.android.baking.DataBaseHelper;
import com.android.baking.MainActivity;
import com.android.baking.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class SplashActivity extends MainActivity {
private static boolean splashLoaded = false;
private static String DB_PATH;
private static String DB_NAME;
private static final int SPLASH_TIME = 1000;
public final int WRITE_PERMISSION_REQUEST_CODE = 1110;
private final String[] NEEDED_PERMISSIONS = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkPermissions(NEEDED_PERMISSIONS)){
ActivityCompat.requestPermissions(SplashActivity.this, NEEDED_PERMISSIONS, WRITE_PERMISSION_REQUEST_CODE);
}else {
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute();
}
if (!splashLoaded) {
setContentView(R.layout.splash_screen);
int secondsDelayed = 3;
new Handler().postDelayed(new Runnable() {
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
}, secondsDelayed * SPLASH_TIME);
splashLoaded = true;
} else {
Intent goToMainActivity = new Intent(SplashActivity.this, MainActivity.class);
goToMainActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(goToMainActivity);
finish();
}
//copy database from assets to database folder if it does not exist
//see also: https://stackoverflow.com/questions/18805874/copy-database-from-assets-to-databases-folder/18806587
if (!doesDatabaseExist(this, DataBaseHelper.DB_NAME)){
DB_PATH = getApplicationInfo().dataDir + "/databases/";
DB_NAME = DataBaseHelper.DB_NAME;
copyDataBase(DB_NAME, DB_PATH);
}
}
private static boolean doesDatabaseExist(Context context, String dbName) {
File dbFile = context.getDatabasePath(dbName);
return dbFile.exists();
}
private void copyDataBase(String dbName, String dbPath)
{
Log.i("Database",
"New database is being copied to device!");
byte[] buffer = new byte[1024];
OutputStream myOutput = null;
int length;
// Open your local db as the input stream
InputStream myInput = null;
try
{
myInput = getApplicationContext().getAssets().open(dbName);
// transfer bytes from the inputfile to the
// outputfile
myOutput = new FileOutputStream(dbPath + dbName);
while((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
myOutput.close();
myOutput.flush();
myInput.close();
Log.i("Database",
"New database has been copied to device!");
}
catch(IOException e)
{
e.printStackTrace();
}
}
// to get FaceFeature and FaceIdFeature.
private boolean checkPermissions(String[] neededPermissions) {
if (neededPermissions == null || neededPermissions.length == 0) {
return true;
}
boolean allGranted = true;
for (String neededPermission : neededPermissions) {
allGranted &= ContextCompat.checkSelfPermission(getApplicationContext(), neededPermission) == PackageManager.PERMISSION_GRANTED;
}
return allGranted;
}
private class BackgroundTask extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object[] objects) {
try {
Thread.sleep(SPLASH_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case WRITE_PERMISSION_REQUEST_CODE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute();
}
break;
default:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == WRITE_PERMISSION_REQUEST_CODE && resultCode == RESULT_OK) {
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute();
}
}
}
RecipeAdapter.java:
package com.android.baking.ui.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.android.baking.R;
import com.android.baking.ui.listeners.RecipeItemClickListener;
import com.android.baking.ui.models.RecipeModel;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
// Create the basic adapter extending from RecyclerView.Adapter
// Note that we specify the custom ViewHolder which gives us access to our views
// see: https://stackoverflow.com/questions/40584424/simple-android-recyclerview-example
public class RecipeAdapter extends
RecyclerView.Adapter<RecipeAdapter.ViewHolder> {
private Context recipeContext;
private ArrayList<RecipeModel> recipeList = new ArrayList<>();
private ArrayList<RecipeModel> recipeSearchList = new ArrayList<>();
private RecipeItemClickListener recipeListener;
public RecipeAdapter(Context context, ArrayList<RecipeModel> recipeContentList, RecipeItemClickListener listener) {
this.recipeContext = context;
this.recipeListener = listener;
this.recipeList.addAll(recipeContentList);
recipeSearchList.addAll(recipeList);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(recipeContext).inflate(R.layout.item_recycler_view_recipes, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final RecipeModel recipeModel = recipeList.get(position);
holder.tv_title.setText(recipeModel.getTitle());
}
#Override
public int getItemCount() {
return recipeList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_title;
public ViewHolder(View itemView) {
//ToDo: hier weitermachen
super(itemView);
tv_title = itemView.findViewById(R.id.item_title);
}
}
}
RecipeFragment.java:
package com.android.baking.ui.recipes;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.baking.DataBaseHelper;
import com.android.baking.MainActivity;
import com.android.baking.R;
import com.android.baking.ui.adapter.RecipeAdapter;
import com.android.baking.ui.listeners.RecipeItemClickListener;
import com.android.baking.ui.models.RecipeModel;
import java.util.ArrayList;
public class RecipesFragment extends Fragment {
private RecipesViewModel recipesViewModel;
private ArrayList<RecipeModel> recipeList = new ArrayList<>();
private static RecipesFragment mInstance;
DataBaseHelper dataBaseHelper = new DataBaseHelper(getContext());
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
recipesViewModel = new ViewModelProvider(this).get(RecipesViewModel.class);
View root = inflater.inflate(R.layout.fragment_recipes, container, false);
RecyclerView rec_recipes = root.findViewById(R.id.recipes_recycler_view);
rec_recipes.setLayoutManager(new LinearLayoutManager(getContext()));
recipeList = dataBaseHelper.getAllRecipes();
RecipeAdapter recipeAdapter = new RecipeAdapter(getContext(), recipeList, new RecipeItemClickListener() {
#Override
public void OnItemClicked(RecipeModel recipeModel) {
Toast.makeText(getContext(), "You clicked " + recipeModel.getTitle(), Toast.LENGTH_SHORT).show();
}
});
rec_recipes.setAdapter(recipeAdapter);
return root;
}
}
In RecipieFragment.DataBaseHelper, calling getContext() here it may be returning you a null, hence the NPE. Try creating the DataBaseHelper in onCreateView() instead.

Data type mismatch when inserting data into android app database

I'm not entirely sure what could be happening, I know that there is a mismatch when I try to insert, but when I double check my code I can't see why it would spit that error out. I am simply trying to insert a username and password (both are Strings).
CONTEXT:
In my RegisterLoginActivity.java I made it when the user taps the TextView "Create account" it will grab the username and password and turn them into strings.
Then in my DatabaseOperations.java I use the function putInformation() to insert the data.
My TableData.java simply contains my table information.
RegisterLoginActivity.java;
package com.example.envy.energyvue;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RegisterLoginActivity extends AppCompatActivity {
EditText USER_NAME, USER_PASS;
TextView REG;
String user_name, user_pass;
Context ctx = this;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
//getActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_login);
USER_NAME = (EditText) findViewById(R.id.userText);
USER_PASS = (EditText) findViewById(R.id.passText);
REG = (TextView) findViewById(R.id.createAccount);
REG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_PASS.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB,user_name, user_pass);
}
});
// IGNORE THIS PORTION, IT IS FOR LOGGING IN AFTER I REGISTER
//********************************************
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_NAME.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
Cursor CR = DB.getInformation(DB);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do{
if(user_name.equals(CR.getString(0)) && user_pass.equals(CR.getString(1))){
loginstatus = true;
}
}while(CR.moveToFirst());
if(loginstatus){
Toast.makeText(getBaseContext(), "Login Success", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Login Failed", Toast.LENGTH_LONG).show();
}
}
});
}
}
DatabaseOperations.java;
package com.example.envy.energyvue;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Envy on 7/13/2016.
*
* private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
*/
public class DatabaseOperations extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserData.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME;
public DatabaseOperations(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void putInformation(DatabaseOperations dop, String user_id, String password){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.COLUMN_NAME_USER_ID, user_id);
cv.put(TableData.TableInfo.COLUMN_NAME_PASSWORD, password);
System.out.print("LOLOLSDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
long newRowId;
newRowId = SQ.insert(
TableData.TableInfo.TABLE_NAME,
null,
cv);
}
public Cursor getInformation(DatabaseOperations dop){
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] projection = {
TableData.TableInfo._ID,
TableData.TableInfo.COLUMN_NAME_USER_ID,
TableData.TableInfo.COLUMN_NAME_PASSWORD
};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, projection, null, null, null, null, null);
return CR;
}
}
TableData.java;
package com.example.envy.energyvue;
import android.provider.BaseColumns;
/**
* Created by Envy on 7/13/2016.
*/
public class TableData {
public TableData(){}
public static abstract class TableInfo implements BaseColumns {
public static final String TABLE_NAME = "login_information";
public static final String COLUMN_NAME_USER_ID = "user_id";
public static final String COLUMN_NAME_PASSWORD = "password";
}
}
Error:
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteLog: (20) statement aborts at 5: [INSERT INTO login_information(password,user_id) VALUES (?,?)] datatype mismatch
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteDatabase: Error inserting password= bbb user_id=bbb
android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
#################################################################
Error Code : 20 (SQLITE_MISMATCH)
Caused By : Data type mismatch.
(datatype mismatch (code 20))
#################################################################
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:915)
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:1609)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.envy.energyvue.DatabaseOperations.putInformation(DatabaseOperations.java:59)
at com.example.envy.energyvue.RegisterLoginActivity$1.onClick(RegisterLoginActivity.java:37)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
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)
Alright guys.. after many hours, I figured it out ....I put my database name with a ".db" extension which was messing things up.

Error when start activity and upload Database

When I click a Button I starting a new activity, called Profilo.java. My code is:
package com.example.prenotazione_esame;
import android.app.Activity; import android.app.AlertDialog; import
android.content.DialogInterface; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.os.*;
import android.view.Menu; import android.view.MenuItem; import
android.widget.Button; import android.widget.EditText; import
android.view.View; import android.view.View.OnClickListener; import
android.widget.Toast;
public class Profilo extends Activity {
private LoginDataBase dbLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getIntent().getExtras().getInt("id");
setContentView(R.layout.profilo);
SQLiteDatabase db = dbLogin.getWritableDatabase();
}
}
this LoginDataBase.java
public class LoginDataBase extends SQLiteOpenHelper {
private static final String DB_NAME="Login_DB";
private static final int DB_VERSION=1;
public LoginDataBase(Context context){
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql="";
sql+= "CREATE TABLE T_LOGIN (";
sql+= " _id_LOGIN INTEGER PRIMARY KEY AUTOINCREMENT,";
sql+= " USERNAME TEXT NOT NULL,";
sql+= " PASSWORD TEXT NOT NULL";
sql+=")";
db.execSQL(sql);
String sql2="";
sql2+= "CREATE TABLE T_PROFILO (";
sql2+= " _id_PROFILO INTEGER PRIMARY KEY AUTOINCREMENT,";
sql2+= " NOME TEXT NOT NULL,";
sql2+= " COGNOME TEXT NOT NULL,";
sql2+= " ETA TEXT NOT NULL,";
sql2+= " SESSO TEXT(1) NOT NULL,";
sql2+= " CODICE_FISCALE TEXT NOT NULL,";
sql2+= " CITTA TEXT NOT NULL,";
sql2+= " INDIRIZZO TEXT NOT NULL,";
sql2+= " TELEFONO TEXT NOT NULL,";
sql2+= " _id_L INTEGER NOT NULL,";
sql2+= " FOREIGN KEY(_id_L) REFERENCES T_LOGIN(_id_LOGIN)";
sql2+= ")";
db.execSQL(sql2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Aggiornamento delle tabelle
}
}
the problem is when I try to take my database db. My app crash.
Where is the problem?
You need to inicializate dbLogin.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getIntent().getExtras().getInt("id");
setContentView(R.layout.profilo);
///NEW
LoginDataBase dbLogin = new LoginDataBase (this, "NAMEOFDATABASE", null, 1);
///END OF NEW
SQLiteDatabase db = dbLogin.getWritableDatabase();
}
}
You class LoginDataBase must have a constructor similar than this:
public class LoginDataBase extends SQLiteOpenHelper {
private static final String DB_NAME="Login_DB";
private static final int DB_VERSION=1;
public LoginDataBase (Context contexto, String name,
CursorFactory factory, int version) {
super(contexto, name, factory, version);
}
Or you can also change this and continue with your constructor:
///NEW
LoginDataBase dbLogin = new LoginDataBase (this);
///END OF NEW

Error on Android's rawQuery()

i got nullPointerException when trying to fetch some data from database with rawQuery.
Here's an error:
03-11 18:09:01.522: E/AndroidRuntime(2057): Uncaught handler: thread
main exiting due to uncaught exception 03-11 18:09:01.532:
E/AndroidRuntime(2057): java.lang.NullPointerException 03-11
18:09:01.532: E/AndroidRuntime(2057): at
com.math.scan.FormulaModel.setFormulaList(FormulaModel.java:27)
Look at my code:
DbHelper
package com.math.scan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "formulas";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_UNKNOWN = "unknown";
public static final String COLUMN_FORMULA = "formula";
public static final String COLUMN_CTG = "ctg";
private static final String DB_NAME = "formulas.db";
private static int DB_VERSION = 1;
private static final String DB_CREATE = "CREATE TABLE "+TABLE_NAME+
"("+COLUMN_ID+" integer primary key autoincrement,"
+COLUMN_UNKNOWN+" text not null,"
+COLUMN_FORMULA+" text not null,"
+COLUMN_CTG+" text not null );";
public Context mCtx;
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mCtx = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DB_CREATE);
// reading formulas
AssetManager asset = mCtx.getAssets();
try {
InputStream input = asset.open("formulas");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
String content = new String(buffer);
Scanner scan = new Scanner(content);
String current;
String[] f = new String[2];
String[] formula = new String[2];
while(scan.hasNextLine()) {
current = scan.nextLine();
// get category
f = current.split("!!");
formula = f[1].split(" = ");
database.execSQL("INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
Log.d("DB", "INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DbHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
FormulaModel
package com.math.scan;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class FormulaModel {
private SQLiteDatabase database;
private DbHelper dbHelper;
public FormulaModel(Context context) {
dbHelper = new DbHelper(context);
}
public void open() throws SQLException {
dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void setFormulaList(String ctg) {
open();
// app stops working here
Cursor cursor = database.rawQuery("SELECT unknown, formula FROM formulas WHERE ctg = '"+ctg+"'", null);
int results = cursor.getCount();
cursor.moveToFirst();
Global.FormuleResult = new String[results];
Global.FormuleTable = new String[results];
for(int i = 0; i < results; i++) {
Global.FormuleTable[i] = cursor.getString(1);
Global.FormuleResult[i] = cursor.getString(0);
}
close();
}
}
This is activity, where I call setFormulaList() method in FormulaModel class.
package com.math.scan;
import net.sourceforge.jeval.EvaluationException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ProblemActivity extends Activity {
private EditText prob;
private Button solve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
// text field
prob = (EditText) findViewById(R.id.problem);
// confirm btn
solve = (Button) findViewById(R.id.solve);
// check if confirm button was pressed
solve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get text from the field
String problem = prob.getText().toString();
// check if expression is not empty
if(problem.length() == 0) {
// string is empty!
Toast.makeText(ProblemActivity.this, getString(R.string.empty_field), Toast.LENGTH_SHORT).show();
} else {
FormulaModel f = new FormulaModel(ProblemActivity.this);
f.setFormulaList("mech");
pears.doMagic(problem);
try {
String str = Global.eval.getVariableValue(Global.UNKNOWN);
TextView answ = (TextView) findViewById(R.id.answer);
answ.setText(getString(R.string.prob_answ) + str);
} catch (EvaluationException e) {
Toast.makeText(ProblemActivity.this, getString(R.string.prob_error), Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
I can't figure out what is wrong here.
Any ideas?
You have to set your database variable in open():
database = dbHelper.getWritableDatabase();

Categories